Search Results

Search found 2566 results on 103 pages for 'struct'.

Page 10/103 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Struct inside a class

    - by Balakrishnan
    I have a class definition of the form class X { public: //class functions private: A_type *A; //other class variables }; and struct A_type is defined as struct A_type { string s1,s2,s3; }; Inside the constructor, I allocate appropriate memory for A and try A[0].s1="somestring"; It shows segmentation fault. Is this kind of declaration invalid, or am I missing something

    Read the article

  • Constructor for an immutable struct

    - by Danvil
    Consider the following simple immutable struct: struct Stash { public int X { get; private set; } public Stash(int _x) { X = _x; } } This is not working, because the compiler wants me to initialize the "backing field" before I can access the property. How can I solve this?

    Read the article

  • Overriding Equals method in Structs

    - by devoured elysium
    I've looked for overriding guidelines for structs, but all I can find is for classes. At first I thought I wouldn't have to check to see if the passed object was null, as structs are value types and can't be null. But now that I come to think of it, as equals signature is public bool Equals(object obj) it seems there is nothing preventing the user of my struct to be trying to compare it with an arbitrary reference type. My second point concerns the casting I (think I) have to make before I compare my private fields in my struct. How am I supposed to cast the object to my struct's type? C#'s as keyword seems only suitable for reference types. Thanks

    Read the article

  • Returning structs in registers - ARM ABI in GCC

    - by jbcreix
    Hi, In the ARM ABI documentation I come across functions defined like: __value_in_regs struct bar foo(int a, int b) { ... } but GCC(4.3.3) doesn't allow it and all I could find are references to some RealView compiler. Is there any way of doing this from GCC? I have tried -freg-struct-return but it doesn't make a difference. As it is an ABI I can't change the original programs, and returning a regular struct mangles the stack. I would rather not using assembly for this if avoidable as it isn't otherwise necessary. Thanks!

    Read the article

  • How does NSValue do its magic?

    - by Paperflyer
    I have an MVC application. The model has a property that is a struct NSSize. It is writable like this: - (void)setSize:(NSSize)aSize; The view sets this NSSize using key-value-coding. However, you can not key-value-code a struct, so I wrapped it in an NSValue-object like this: [theView setValue:[NSValue valueWithSize:mySize] forKey:@"theModel.size"]; To my understanding, this should not work since the accessor expects a struct and not an NSValue. But it works perfectly. Magically. How is this possible?

    Read the article

  • How to sanely read and dump structs to disk when some fields are pointers?

    - by bp
    Hello, I'm writing a FUSE plugin in C. I'm keeping track of data structures in the filesystem through structs like: typedef struct { block_number_t inode; filename_t filename; //char[SOME_SIZE] some_other_field_t other_field; } fs_directory_table_item_t; Obviously, I have to read (write) these structs from (to) disk at some point. I could treat the struct as a sequence of bytes and do something like this: read(disk_fd, directory_table_item, sizeof(fs_directory_table_item_t)); ...except that cannot possibly work as filename is actually a pointer to the char array. I'd really like to avoid having to write code like: read(disk_df, *directory_table_item.inode, sizeof(block_number_t)); read(disk_df, directory_table_item.filename, sizeof(filename_t)); read(disk_df, *directory_table_item.other_field, sizeof(some_other_field_t)); ...for each struct in the code, because I'd have to replicate code and changes in no less than three different places (definition, reading, writing). Any DRYer but still maintainable ideas?

    Read the article

  • c/c++ how to convert short to char

    - by changed
    Hi I am using ms c++. I am using struct like struct header { unsigned port : 16; unsigned destport : 16; unsigned not_used : 7; unsigned packet_length : 9; }; struct header HR; here this value of header i need to put in separate char array. i did memcpy(&REQUEST[0], &HR, sizeof(HR)); but value of packet_length is not appearing properly. like if i am assigning HR.packet_length = 31; i am getting -128(at fifth byte) and 15(at sixth byte). if you can help me with this or if their is more elegant way to do this. thanks

    Read the article

  • Comparing an array of users to an array of structs with user object as attribute, and returning matc

    - by keruilin
    I have an array of users who are friends. Let us call this array: friends I then have an array of structs. Each struct has a user object as an attribute (it also has a rank attribute). Here's what the struct class looks like, to add some context: class Leader < Struct.new(:rank, :user); end Let us call this array of structs: all_leaders_plus_rank I want to compare friends and all_leaders_plus_rank, and add the match from all_leaders_plus_rank to a new array of structs called friendly_leaders.

    Read the article

  • Writing different structs to a file in C++? [on hold]

    - by user58053
    I need a way to write structures of three different kinds to a binary file, which later has to be searched. (As in, for example, struct A has two fields, an int and a char; struct B has int and a long; I need to output all structures whose int equals the one given from keyboard). I understand how to write structs of the same kind to a file and how to search them, but here I am just lost, best thing I came up with is declaring a struct containing all possibly needed fields and leaving the ones I don't need empty, but it really feels wrong, there HAS to be a better way to do that. I've read about binary files and could not find anything relevant, most examples and tutorials deal with writing one data type. Could anyone point me in the right direction? EDIT: I am looking for what @Jerry_coffin called database mode, and will probably use one of the existing database systems for that, best way to go, probably. Thank you everybody for the suggestions

    Read the article

  • Incompatible types when assigning to type 'struct compartido'

    - by user1660559
    I have one problem with this code. I should create one structure and share it across 5 new process created from the father: #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> #include <time.h> struct compartido { int pid1, pid2, pid3, pid4, pid5; int propietario; int contador; int pidpadre; }; struct compartido var; int main(int argc, char *argv[]) { key_t llave1,llavesem; int idmem,idsem; llave1=ftok("/tmp",'a'); idmem=shmget(llave1,sizeof(int),IPC_CREAT|0600); if (idmem==-1) { perror ("shmget"); return 1; } var=shmat(idmem,0,0); /*This line is giving the error*/ /*rest of the code*/ } The exact error is giving is: error: incompatible types when assigning to type 'struct compartido' from type 'void *' I need to put this structure in the shared variable to be able to see and modify all those data from the 6 process (5 children and the father). What I'm doing bad? Thanks in advance and best regards,

    Read the article

  • SWIG interface to receive an opaque struct reference in Java through function argument

    - by Beeo
    I am trying to use SWIG in order to use the Spotify API (libspotify) for Android: https://developer.spotify.com/technologies/libspotify/ I am having trouble defining the SWIG interface file to be able to successfully call the following native C function: sp_error sp_session_create(const sp_session_config * config, sp_session ** sess); Which in C would be called like this: //config struct defined previously sp_session *sess; sp_session_create(&config, &sess); But in Java I would need to call it like this: //config object defined previously sp_session javaSess = new sp_session(); sp_session_create(config, javaSess); sp_session is an opaque struct and is only defined in libspotify's API.h file as: typedef struct sp_session sp_session; I'm expecting the libspotify library to create it and give me a reference to it. The only thing I need that reference for then is to pass to other functions in the API. I believe the answer lies within the SWIG interface and typemaps, but I have been unsuccessful in trying to apply the examples I found in the documentation: http://www.swig.org/Doc2.0/SWIGDocumentation.html#Java_struct_pointer_pointer `http://www.swig.org/Doc2.0/SWIGDocumentation.html#Java_using_typemaps_return_arguments Help!

    Read the article

  • Creating Binary Block from struct

    - by MOnsDaR
    I hope the title is describing the problem, i'll change it if anyone has a better idea. I'm storing information in a struct like this: struct AnyStruct { AnyStruct : testInt(20), testDouble(100.01), testBool1(true), testBool2(false), testBool3(true), testChar('x') {} int testInt; double testDouble; bool testBool1; bool testBool2; bool testBool3; char testChar; std::vector<char> getBinaryBlock() { //how to build that? } } The struct should be sent via network in a binary byte-buffer with the following structure: Bit 00- 31: testInt Bit 32- 61: testDouble most significant portion Bit 62- 93: testDouble least significant portion Bit 94: testBool1 Bit 95: testBool2 Bit 96: testBool3 Bit 97-104: testChar According to this definition the resulting std::vector should have a size of 13 bytes (char == byte) My question now is how I can form such a packet out of the different datatypes I've got. I've already read through a lot of pages and found datatypes like std::bitset or boost::dynamic_bitset, but neither seems to solve my problem. I think it is easy to see, that the above code is just an example, the original standard is far more complex and contains more different datatypes. Solving the above example should solve my problems with the complex structures too i think. One last point: The problem should be solved just by using standard, portable language-features of C++ like STL or Boost (

    Read the article

  • C++ struct, public data members and inheritance

    - by Marius
    Is it ok to have public data members in a C++ class/struct in certain particular situations? How would that go along with inheritance? I've read opinions on the matter, some stated already here http://stackoverflow.com/questions/952907/practices-on-when-to-implement-accessors-on-private-member-variables-rather-than http://stackoverflow.com/questions/670958/accessors-vs-public-members or in books/articles (Stroustrup, Meyers) but I'm still a little bit in the shade. I have some configuration blocks that I read from a file (integers, bools, floats) and I need to place them into a structure for later use. I don't want to expose these externally just use them inside another class (I actually do want to pass these config parameters to another class but don't want to expose them through a public API). The fact is that I have many such config parameters (15 or so) and writing getters and setters seems an unnecessary overhead. Also I have more than one configuration block and these are sharing some of the parameters. Making a struct with all the data members public and then subclassing does not feel right. What's the best way to tackle that situation? Does making a big struct to cover all parameters provide an acceptable compromise (I would have to leave some of these set to their default values for blocks that do not use them)?

    Read the article

  • C struct written in file, open with Java

    - by DaunnC
    For example in C I have structure: typedef struct { int number; double x1; double y1; double x2; double y2; double x3; double y3; } CTRstruct;` Then I write it to file fwrite(&tr, 1, sizeof(tr), fp); (tr - its CTRstruct var, fp - File pointer); Then I need to read it with Java! I really don't know how to read struct from file... I tried to read it with ObjectInputStream(), last idea is to read with RandomAccessFile() but I also don't know how to... (readLong(), readDouble() also doesn't work, it works ofcource but doesn't read correct data). So, any idea how to read C struct from binary file with Java? If it's interesting, my version to read integer (but it's ugly, & I don't know what to do with double): public class MyDataInputStream extends DataInputStream{ public MyDataInputStream(InputStream AIs) { super(AIs); } public int readInt1() throws IOException{ int ch1 = in.read(); int ch2 = in.read(); int ch3 = in.read(); int ch4 = in.read(); if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException(); return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0)); } with double we can deal the same way (like with int or with long (8bytes) & then convert to double with native func).

    Read the article

  • TPL - Using static method vs struct method

    - by Sunit
    I have about 1500 files on a share for which I need to collect FileVersionInfo string. So I created a Static method in my Gateway like this: private static string GetVersionInfo(string filepath) { FileVersionInfo verInfo = FileVersionInfo.GetVersionInfo(filepath); return string.Format("{0}.{1}.{2}.{3}", verInfo.ProductMajorPart, verInfo.ProductMinorPart, verInfo.ProductBuildPart, verInfo.ProductPrivatePart).Trim(); } And then used FileAndVersion struct in a PLINQ call with DegreeOfParallelism as this is I/O related resultList = dllFilesRows.AsParallel().WithDegreeOfParallelism(20) .Select(r => { var symbolPath = r.Filename; return new FilenameAndVersion{Filename=symbolPath, Version=GetVersionInfo(symbolPath)}; }) .ToArray(); Later I modified the Struct, FileAndVersion as: private struct FilenameAndVersion { private string _version, _filename; public string Version { get { return _version; } } public string Filename { get { return _filename; } } public void SetVersion() { FileVersionInfo verInfo = FileVersionInfo.GetVersionInfo(this.Filename); this._version = string.Format("{0}.{1}.{2}.{3}", verInfo.ProductMajorPart, verInfo.ProductMinorPart, verInfo.ProductBuildPart, verInfo.ProductPrivatePart).Trim(); } public FilenameAndVersion(string filename, string version) { this._filename = filename; this._version = string.Empty; SetVersion(); } } And used it: resultList = dllFilesRows.AsParallel().WithDegreeOfParallelism(20) .Select(r => { var symbolPath = r.Filename; return new FilenameAndVersion(symbolPath, String.Empty); }) .ToArray(); The question is, is this going to help me in anyway and is a good pattern to use ? Sunit

    Read the article

  • Problem with passing array of pointers to struct among functions in C

    - by karatemonkey
    The Code that follows segfaults on the call to strncpy and I can't see what I am doing wrong. I need another set of eyes to look it this. Essentially I am trying to alloc memory for a struct that is pointed to by an element in a array of pointers to struct. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_POLICY_NAME_SIZE 64 #define POLICY_FILES_TO_BE_PROCESSED "SPFPolicyFilesReceivedOffline\0" typedef struct TarPolicyPair { int AppearanceTime; char *IndividualFile; char *FullPolicyFile; } PolicyPair; enum { bwlist = 0, fzacts, atksig, rules, MaxNumberFileTypes }; void SPFCreateIndividualPolicyListing(PolicyPair *IndividualPolicyPairtoCreate ) { IndividualPolicyPairtoCreate = (PolicyPair *) malloc(sizeof(PolicyPair)); IndividualPolicyPairtoCreate->IndividualFile = (char *)malloc((MAX_POLICY_NAME_SIZE * sizeof(char))); IndividualPolicyPairtoCreate->FullPolicyFile = (char *)malloc((MAX_POLICY_NAME_SIZE * sizeof(char))); IndividualPolicyPairtoCreate->AppearanceTime = 0; memset(IndividualPolicyPairtoCreate->IndividualFile, '\0', (MAX_POLICY_NAME_SIZE * sizeof(char))); memset(IndividualPolicyPairtoCreate->FullPolicyFile, '\0', (MAX_POLICY_NAME_SIZE * sizeof(char))); } void SPFCreateFullPolicyListing(SPFPolicyPair **CurrentPolicyPair, char *PolicyName, char *PolicyRename) { int i; for(i = 0; i < MaxNumberFileTypes; i++) { CreateIndividualPolicyListing((CurrentPolicyPair[i])); // segfaults on this call strncpy((*CurrentPolicyPair)[i].IndividualFile, POLICY_FILES_TO_BE_PROCESSED, (SPF_POLICY_NAME_SIZE * sizeof(char))); } } int main() { SPFPolicyPair *CurrentPolicyPair[MaxNumberFileTypes] = {NULL, NULL, NULL, NULL}; int i; CreateFullPolicyListing(&CurrentPolicyPair, POLICY_FILES_TO_BE_PROCESSED, POLICY_FILES_TO_BE_PROCESSED); return 0; }

    Read the article

  • BST insert operation. don't insert a node if a duplicate exists already

    - by jeev
    the following code reads an input array, and constructs a BST from it. if the current arr[i] is a duplicate, of a node in the tree, then arr[i] is discarded. count in the struct node refers to the number of times a number appears in the array. fi refers to the first index of the element found in the array. after the insertion, i am doing a post-order traversal of the tree and printing the data, count and index (in this order). the output i am getting when i run this code is: 0 0 7 0 0 6 thank you for your help. Jeev struct node{ int data; struct node *left; struct node *right; int fi; int count; }; struct node* binSearchTree(int arr[], int size); int setdata(struct node**node, int data, int index); void insert(int data, struct node **root, int index); void sortOnCount(struct node* root); void main(){ int arr[] = {2,5,2,8,5,6,8,8}; int size = sizeof(arr)/sizeof(arr[0]); struct node* temp = binSearchTree(arr, size); sortOnCount(temp); } struct node* binSearchTree(int arr[], int size){ struct node* root = (struct node*)malloc(sizeof(struct node)); if(!setdata(&root, arr[0], 0)) fprintf(stderr, "root couldn't be initialized"); int i = 1; for(;i<size;i++){ insert(arr[i], &root, i); } return root; } int setdata(struct node** nod, int data, int index){ if(*nod!=NULL){ (*nod)->fi = index; (*nod)->left = NULL; (*nod)->right = NULL; return 1; } return 0; } void insert(int data, struct node **root, int index){ struct node* new = (struct node*)malloc(sizeof(struct node)); setdata(&new, data, index); struct node** temp = root; while(1){ if(data<=(*temp)->data){ if((*temp)->left!=NULL) *temp=(*temp)->left; else{ (*temp)->left = new; break; } } else if(data>(*temp)->data){ if((*temp)->right!=NULL) *temp=(*temp)->right; else{ (*temp)->right = new; break; } } else{ (*temp)->count++; free(new); break; } } } void sortOnCount(struct node* root){ if(root!=NULL){ sortOnCount(root->left); sortOnCount(root->right); printf("%d %d %d\n", (root)->data, (root)->count, (root)->fi); } }

    Read the article

  • c++ stl priority queue insert bad_alloc exception

    - by bsg
    Hi, I am working on a query processor that reads in long lists of document id's from memory and looks for matching id's. When it finds one, it creates a DOC struct containing the docid (an int) and the document's rank (a double) and pushes it on to a priority queue. My problem is that when the word(s) searched for has a long list, when I try to push the DOC on to the queue, I get the following exception: Unhandled exception at 0x7c812afb in QueryProcessor.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012ee88.. When the word has a short list, it works fine. I tried pushing DOC's onto the queue in several places in my code, and they all work until a certain line; after that, I get the above error. I am completely at a loss as to what is wrong because the longest list read in is less than 1 MB and I free all memory that I allocate. Why should there suddenly be a bad_alloc exception when I try to push a DOC onto a queue that has a capacity to hold it (I used a vector with enough space reserved as the underlying data structure for the priority queue)? I know that questions like this are almost impossible to answer without seeing all the code, but it's too long to post here. I'm putting as much as I can and am anxiously hoping that someone can give me an answer, because I am at my wits' end. The NextGEQ function is too long to put here, but it reads a list of compressed blocks of docids block by block. That is, if it sees that the lastdocid in the block (in a separate list) is larger than the docid passed in, it decompresses the block and searches until it finds the right one. If it sees that it was already decompressed, it just searches. Below, when I call the function the first time, it decompresses a block and finds the docid; the push onto the queue after that works. The second time, it doesn't even need to decompress; that is, no new memory is allocated, but after that time, pushing on to the queue gives a bad_alloc error. struct DOC{ long int docid; long double rank; public: DOC() { docid = 0; rank = 0.0; } DOC(int num, double ranking) { docid = num; rank = ranking; } bool operator>( const DOC & d ) const { return rank > d.rank; } bool operator<( const DOC & d ) const { return rank < d.rank; } }; struct listnode{ int* metapointer; int* blockpointer; int docposition; int frequency; int numberdocs; int* iquery; listnode* nextnode; }; void QUERYMANAGER::SubmitQuery(char *query){ vector<DOC> docvec; docvec.reserve(20); DOC doct; //create a priority queue to use as a min-heap to store the documents and rankings; //although the priority queue uses the heap as its underlying data structure, //I found it easier to use the STL priority queue implementation priority_queue<DOC, vector<DOC>,std::greater<DOC>> q(docvec.begin(), docvec.end()); q.push(doct); //do some processing here; startlist is a pointer to a listnode struct that starts the //linked list cout << "Opening lists:" << endl; //point the linked list start pointer to the node returned by the OpenList method startlist = &OpenList(value); listnode* minpointer; q.push(doct); //more processing here; else{ //start by finding the first docid in the shortest list int i = 0; q.push(doct); num = NextGEQ(0, *startlist); q.push(doct); while(num != -1) cout << "finding nextGEQ from shortest list" << endl; q.push(doct); //the is where the problem starts - every previous q.push(doct) works; the one after //NextGEQ(num +1, *startlist) gives the bad_alloc error num = NextGEQ(num + 1, *startlist); q.push(doct); //if you didn't break out of the loop; i.e., all lists contain a matching docid, //calculate the document's rank; if it's one of the top 20, create a struct //containing the docid and the rank and add it to the priority queue if(!loop) { cout << "found match" << endl; if(num < 0) { cout << "reached end of list" << endl; //reached the end of the shortest list; close the list CloseList(startlist); break; } rank = calculateRanking(table, num); try{ //if the heap is not full, create a DOC struct with the docid and //rank and add it to the heap if(q.size() < 20) { doc.docid = num; doc.rank = rank; q.push(doct); q.push(doc); } } catch (exception& e) { cout << e.what() << endl; } } } Thank you very much, bsg.

    Read the article

  • Generic linked list in c++

    - by itsaboy
    I have been struggling for too long a time now with a rather simple question about how to create a generic linked list in c++. The list should be able contain several types of structs, but each list will only contain one type of struct. The problem arises when I want to implement the getNode() function [see below], because then I have to specify which of the structs it should return. I have tried to substitute the structs with classes, where the getNode function returns a base class that is inherited by all the other classes, but it still does not do the trick, since the compiler does not allow the getNode function to return anything but the base class then. So here is some code snippet: typedef struct struct1 { int param1; (...) } struct1; typedef struct struct2 { double param1; (...) } struct2; typedef struct node { struct1 data; node* link; } node; class LinkedList { public: node *first; int nbrOfNodes; LinkedList(); void addNode(struct1); struct1 getNode(); bool isEmpty(); }; LinkedList::LinkedList() { first = NULL; nbrOfNodes = 0; } void LinkedList::addNode(struct1 newData) { if (nbrOfNodes == 0) { first = new node; first->data = newData; } else { node *it = first; for (int i = 0; i < nbrOfNodes; i++) { it = it->link; } node *newNode = new node; newNode->data = newData; it->link = newNode; } nbrOfNodes++; } bool LinkedList::isEmpty() { return !nbrOfNodes; } struct1 LinkedList::getNode() { param1 returnData = first->data; node* deleteNode = first; nbrOfNodes--; if (nbrOfNodes) first = deleteNode->link; delete deleteNode; return returnData; } So the question, put in one sentence, is as follows: How do I adjust the above linked list class so that it can also be used for struct2, without having to create a new almost identical list class for struct2 objects? As I said above, each instance of LinkedList will only deal with either struct1 or struct2. Grateful for hints or help

    Read the article

  • How to initialize const float32x4x4_t (ARM NEON intrinsic, GCC) ?

    - by Eonil
    I can initialize float32x4_t like this: const float32x4x4_t = { 0.0f, 0.0f, 0.0f, 0.0f }; But this code makes an error Incompatible types in initializer: const float32x4x4_t = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; float32x4x4_t is 4x4 matrix built as: typedef struct float32x4x4_t { float32x4_t val[4]; } float32x4x4_t; How can I initialize this const struct?

    Read the article

  • When should I explicitly specify a StructLayout?

    - by biozinc
    I'm fiddling with calling DLLs from C#, and came across the need to define my own structs. Lots of articles force a sequential layout for the struct with [StructLayout(LayoutKind.Sequential)] struct Foo ... So, I followed suite, and my programme worked. Now, when I took the line out, it still works. Why do I need it?

    Read the article

  • Sorting an array of structs

    - by keruilin
    I have an array of structs called leaders. The struct class looks like this, for contextual info: class Leader < Struct.new(:rank, :user); end Two questions: How do I sort the array of structs by rank? How do I sort the array of structs by rank and by user.created_at?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >