Search Results

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

Page 24/103 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • How to fix these compiler errors?

    - by Sandra Schlichting
    I have this source code from 2001 that I would like to compile. It gives this: $ make g++ -O99 -Wall -DLINUX -pedantic -c -o audio.o audio.cpp In file included from audio.cpp:7: audio.h:14: error: use of enum ‘mad_flow’ without previous declaration audio.h:15: error: use of enum ‘mad_flow’ without previous declaration audio.h:17: error: use of enum ‘mad_flow’ without previous declaration audio.cpp: In function ‘mad_flow audio::input(void*, mad_stream*)’: audio.cpp:19: error: new declaration ‘mad_flow audio::input(void*, mad_stream*)’ audio.h:14: error: ambiguates old declaration ‘int audio::input(void*, mad_stream*)’ audio.h:11: error: ‘size_t audio::stream::BufferPos’ is private audio.cpp:23: error: within this context audio.h:11: error: ‘size_t audio::stream::BufferSize’ is private audio.cpp:23: error: within this context audio.h:10: error: ‘char* audio::stream::Buffer’ is private audio.cpp:26: error: within this context audio.h:11: error: ‘size_t audio::stream::BufferSize’ is private audio.cpp:26: error: within this context audio.h:11: error: ‘size_t audio::stream::BufferPos’ is private audio.cpp:27: error: within this context audio.h:11: error: ‘size_t audio::stream::BufferSize’ is private audio.cpp:27: error: within this context audio.cpp: In function ‘mad_flow audio::output(void*, const mad_header*, mad_pcm*)’: audio.cpp:49: error: new declaration ‘mad_flow audio::output(void*, const mad_header*, mad_pcm*)’ audio.h:15: error: ambiguates old declaration ‘int audio::output(void*, const mad_header*, mad_pcm*)’ audio.cpp: In function ‘mad_flow audio::error(void*, mad_stream*, mad_frame*)’: audio.cpp:83: error: new declaration ‘mad_flow audio::error(void*, mad_stream*, mad_frame*)’ audio.h:17: error: ambiguates old declaration ‘int audio::error(void*, mad_stream*, mad_frame*)’ audio.cpp: In constructor ‘audio::stream::stream(const char*)’: audio.cpp:119: error: ‘input’ was not declared in this scope audio.cpp:122: error: ‘output’ was not declared in this scope audio.cpp:123: error: ‘error’ was not declared in this scope make: *** [audio.o] Error 1 audio.h contains #include <stdlib.h> #include "mad.h" namespace audio { class stream { private: char* Buffer; size_t BufferSize, BufferPos; struct mad_decoder Decoder; friend enum mad_flow input(void* Data, struct mad_stream* MadStream); friend enum mad_flow output(void* Data, const struct mad_header* Header, struct mad_pcm* PCM); friend enum mad_flow error(void* Data, struct mad_stream* MadStream, struct mad_frame* Frame); public: stream(const char* FileName); ~stream(); void play(); }; } I have tried to just insert enum mad_flow {}; but that just gave a new problem. Can anyone see how to fix this?

    Read the article

  • extern(al) problem

    - by Knowing me knowing you
    Why can't I compile this code? //main #include "stdafx.h" #include "X.h" #include "Y.h" //#include "def.h" extern X operator*(X, Y);//HERE ARE DECLARED EXTERNAL *(X,Y) AND f(X) extern int f(X); /*GLOBALS*/ X x = 1; Y y = x; int i = 2; int _tmain(int argc, _TCHAR* argv[]) { i + 10; y + 10; y + 10 * y; //x + (y + i); x * x + i; f(7); //f(y); //y + y; //106 + y; return 0; } //X struct X { int i; X(int value):i(value) { } X operator+(int value) { return X(i + value); } operator int() { return i; } }; //Y struct Y { int i; Y(X x):i(x.i) { } Y operator+(X x) { return Y(i + x.i); } }; //def.h int f(X x); X operator*(X x, Y y); //def.cpp #include "stdafx.h" #include "def.h" #include "X.h" #include "Y.h" int f(X x) { return x; } X operator*(X x, Y y) { return x * y; } I'm getting err msg: Error 2 error LNK2019: unresolved external symbol "int __cdecl f(struct X)" Error 3 error LNK2019: unresolved external symbol "struct X __cdecl operator*(struct X,struct Y)" Another interesting thing is that if I place the implementation in def.h file it does compiles without errs. But then what about def.cpp? Why I'm not getting err msg that function f(X) is already defined? Here shouldn't apply ODR rule. Second concern I'm having is that if in def.cpp I change the return type of f from int to double intelliSense underlines this as an error but program still compiles? Why?

    Read the article

  • Partial specialization with reference template parameter fails to compile in VS2005

    - by Blair Holloway
    I have code that boils down to the following: template struct Foo {}; template & I struct FooBar {}; //////// template struct Baz {}; template & I struct Baz< FooBar { static void func(FooBar& value); }; //////// struct MyStruct { static const Foo s_floatFoo; }; // Elsewhere: const Foo MyStruct::s_floatFoo; void callBaz() { typedef FooBar FloatFooBar; FloatFooBar myFloatFooBar; Baz::func(myFloatFooBar); } This compiles successfully under GCC, however, under VS2005, I get: error C2039: 'func' : is not a member of 'Baz' with [ T=FloatFooBar ] error C3861: 'func': identifier not found However, if I change const Foo<T>& I to const Foo<T>* I (passing I by pointer rather than by reference), and defining FloatFooBar as: typedef FooBar FloatFooBar; Both GCC and VS2005 are happy. What's going on? Is this some kind of subtle template substitution failure that VS2005 is handling differently to GCC, or a compiler bug? (The strangest thing: I thought I had the above code working in VS2005 earlier this morning. But that was before my morning coffee. I'm now not entirely certain I wasn't under some sort of caffeine-craving-induced delirium...)

    Read the article

  • dlopen / dlsym with as little linking as possible

    - by johannes
    I have an application which can make use of plugins which are loaded at runtime using dlopen. Each of the plugins defines a function toretrieve the plugin information which is defined using a common structure. Something like that: struct plugin { char *name; char *app_version; int app_verion_id; char *plugin_version; int plugin_version_id; /* ... */ }; struct plugin p = { "sample plugin",APP_VERION,APP_VERSION_ID,"1.2.3",10203 }; struct plugin *get_plugin() { return &p; } This works well and plugins can be loaded. Now i want to build a small tool to read these properties without linking the whole application. For doing that I have some code like this: void *handle; struct plugin *plugin; struct plugin *(get_plugin*)(); handle = dlopen(filename, RTLD_LAZY); if (!handle) { /*...return; ...*/ } get_plugin = dlym(handle, "get_plugin"); if (!get_plugin) { /*...return; ...*/ } plugin = get_plugin(); printf("Plugin: %s\n", plugin->name); This works nice for simple plugins. The issue is that many plugins reference further symbols from the application, which are resolved even though RTLD_LAZY was set. (like global variables from the application which are used to initialize plugin-global things) So the dlopen() call fails with an error like fatal: relocation error: file sample_plugin.so: symbol application_some_symbol: referenced symbol not found. As I just want to have access to the single simple structure I was wondering how I can prevent the linker from doing that much of his work.

    Read the article

  • passing multiple vectors to function by reference (using structure)

    - by madman
    Hi StackOverflow, Can someone tell me the correct way of passing multiple vectors to a function that can take only a single argument? (specifically for pthread_create (..) function) I tried the following but it does not seem to work :-( First, I created the following structure struct ip2 { void* obj; int dim; int n_s; vector<vector<vector<double> > > *wlist; vector<int> *nrsv; struct model *pModel; }; The threads that I have created actually needs all these parameters. Since im using pthreads_create I put all this in a structure and then passed the pointer to the structure as an argument to pthread_create (as shown). some_fxn() { //some code struct ip2 ip; ip.obj=(void*) this; ip.n_s=n_s; ip.wlist=&wlist; ip.nrsv=&nrsv; ip.pModel=pModel; ip.dim=dim; pthread_create(&callThd1[lcntr], &attr1, &Cls::Entry, (void*) &ip); } The Entry method looks something like this. void* Cls::Entry(void *ip) { struct ip2 *x; x = (struct ip2 *)ip; (reinterpret_cast<Cls1 *>(x->obj))->Run(x->dim,x->n_s, x->wlist, x->nrsv, x->pModel); } The Run method looks something like this. void Run(int dim, int n_c, vector<vector<vector<double> > > *wlist, vector<int> *nrsv, struct model* pModel ) { //some code for(int k = 0; k < n_c; ++k) { //some code end = index + nrsv[k]; //some code } I get the following error when I try to compile the program. error: no match for ‘operator+’ in ‘index + *(((std::vector<int, std::allocator<int> >*)(((unsigned int)k) * 12u)) + nrsv)’ Can someone tell me how to do it the right way. Madhavan

    Read the article

  • Q on Python serialization/deserialization

    - by neil
    What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]): enum { apple, orange } VariantTag; struct { uint16 number; opaque string<0..10>; /* variable length */ } V1; struct { uint32 number; opaque string[10]; /* fixed length */ } V2; struct { select (VariantTag) { /* value of selector is implicit */ case apple: V1; /* VariantBody, tag = apple */ case orange: V2; /* VariantBody, tag = orange */ } variant_body; /* optional label on variant */ } VariantRecord; Basically I would have to define a (variant) class VariantRecord, which varies depending on the value of VariantTag. That's not that difficult. The challenge is to find a most generic way to build a class, which serializes/deserializes to and from a byte stream... Pickle, Google protocol buffer, marshal is all not an option. I made little success with having an explicit "def serialize" in my class, but I'm not very happy with it, because it's not generic enough. I hope I could express the problem. My current solution in case VariantTag = apple would look like this, but I don't like it too much import binascii import struct class VariantRecord(object): def __init__(self, number, opaque): self.number = number self.opaque = opaque def serialize(self): out = struct.pack('>HB%ds' % len(self.opaque), self.number, len(self.opaque), self.opaque) return out v = VariantRecord(10, 'Hello') print binascii.hexlify(v.serialize()) >> 000a0548656c6c6f Regards

    Read the article

  • Template with constant expression: error C2975 with VC++2008

    - by Arman
    Hello, I am trying to use elements of meta programming, but hit the wall with the first trial. I would like to have a comparator structure which can be used as following: intersect_by<ID>(L1.data, L2.data, "By ID: "); intersect_by<IDf>(L1.data, L2.data, "By IDf: "); Where: struct ID{};// Tag used for original IDs struct IDf{};// Tag used for the file position //following Boost.MultiIndex examples template<typename Tag,typename MultiIndexContainer> void intersect_by( const MultiIndexContainer& L1,const MultiIndexContainer& L2,std::string msg, Tag* =0 /* fixes a MSVC++ 6.0 bug with implicit template function parms / ) { / obtain a reference to the index tagged by Tag */ const typename boost::multi_index::index<MultiIndexContainer,Tag>::type& L1_ID_index= get<Tag>(L1); const typename boost::multi_index::index<MultiIndexContainer,Tag>::type& L2_ID_index= get<Tag>(L2); std::set_intersection( L1_ID_index.begin(), L1_ID_index.end(), L2_ID_index.begin(), L2_ID_index.end(), std::inserter(s, s.begin()), strComparator() // Here I get the C2975 error ); } template<int N> struct strComparator; template<> struct strComparator<0>{ bool operator () (const particleID& id1, const particleID& id2) const { return id1.ID struct strComparator<1{ bool operator () (const particleID& id1, const particleID& id2) const { return id1.IDf }; What I am missing? kind regards Arman.

    Read the article

  • gSOAP: How to pass info inside soap header

    - by Kangkan
    I wish to send some information like authentication token inside SOAP header. I am using gSOAP/c/Linux. Please help me how to pass? My SOAP_ENV__Header looks like /* SOAP Header: */ struct SOAP_ENV__Header { struct ns3__Header *ns3__MyHeader; /* mustUnderstand */ }; and ns3__Header looks like /* ns3:Header */ struct ns3__Header { char *Value; /* optional element of type xsd:string */ };

    Read the article

  • How do I specify the block object / predicate required by NSDictionary's keysOfEntriesPassingTest ?

    - by Todd
    For learning (not practical -- yet) purposes, I'd like to use the following method on an NSDictionary to give me back a set of keys that have values using a test I've defined. Unfortunately have no idea how to specify the predicate. NSDictionary keysOfEntriesPassingTest: - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate Let's say for example all my values are NSURLs, and I'd like to get back all the URLs that are on port 8080. Here's my stab at coding that -- though it doesn't really make sense to me that it'd be correct: NSSet * mySet = [myDict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) { if( [[obj port] isEqual: [NSNumber numberWithInt: 8080]]) { return key; }] And that's because I get back the following compiler error: incompatible block pointer types initializing 'void (^)(struct objc_object *, struct objc_object *, BOOL *)', expected 'BOOL (^)(struct objc_object *, struct objc_object *, BOOL *)' What am I missing? I'd appreciate a pointer at some docs that go into more detail about the "Block object" that the predicate is supposed to be. Thanks!

    Read the article

  • Problem with std::map and std::pair

    - by Tom
    Hi everyone. I have a small program I want to execute to test something #include <map> #include <iostream> using namespace std; struct _pos{ float xi; float xf; bool operator<(_pos& other){ return this->xi < other.xi; } }; struct _val{ float f; }; int main() { map<_pos,_val> m; struct _pos k1 = {0,10}; struct _pos k2 = {10,15}; struct _val v1 = {5.5}; struct _val v2 = {12.3}; m.insert(std::pair<_pos,_val>(k1,v1)); m.insert(std::pair<_pos,_val>(k2,v2)); return 0; } The problem is that when I try to compile it, I get the following error $ g++ m2.cpp -o mtest In file included from /usr/include/c++/4.4/bits/stl_tree.h:64, from /usr/include/c++/4.4/map:60, from m2.cpp:1: /usr/include/c++/4.4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _pos]’: /usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = _pos, _Val = std::pair<const _pos, _val>, _KeyOfValue = std::_Select1st<std::pair<const _pos, _val> >, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’ /usr/include/c++/4.4/bits/stl_map.h:500: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = _pos, _Tp = _val, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’ m2.cpp:30: instantiated from here /usr/include/c++/4.4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’ m2.cpp:9: note: candidates are: bool _pos::operator<(_pos&) $ I thought that declaring the operator< on the key would solve the problem, but its still there. What could be wrong? Thanks in advance.

    Read the article

  • Strcpy and malloc issues

    - by mrblippy
    Hi, i am having trouble getting a method relating to a linked list working, i get the errors: assignment makes pointer from integer without a cast and passing argument 1 of âstrcpyâ makes pointer from integer without a cast. i have tried to include all the relevant code, but let me know if you need more info. thanks. struct unit { char code[5]; char *name; node_ptr students; }; typedef struct node *node_ptr; struct node { int student_id; char *studentname; node_ptr next; }; void enrol_student(struct unit u[], int n) { int i, p; int student_id = 0; char code_to_enrol[7]; char buffer[100]; node_ptr studentslist; scanf("%s\n", code_to_enrol); for(i=0; i <= n; i++) { studentslist = u[i].students; if(strcmp(u[i].code ,code_to_enrol)<=0) { scanf("enter student details %d %s\n", &studentID, buffer); p = (char *) malloc (strlen(buffer)+1); strcpy(p, buffer); insert_in_order(student_id, buffer, studentslist); } } } void insert_in_order(int n, char *i, node_ptr list) { node_ptr before = list; node_ptr students = (node_ptr) malloc(sizeof(struct node)); students->ID = n; students->name = *i; while(before->next && (before->next->ID < n)) { before = before->next; } students->next = before->next; before->next = students; }

    Read the article

  • Ambiguous access to base class template member function

    - by Johann Gerell
    In Visual Studio 2008, the compiler cannot resolve the call to SetCustomer in _tmain below and make it unambiguous: template <typename TConsumer> struct Producer { void SetConsumer(TConsumer* consumer) { consumer_ = consumer; } TConsumer* consumer_; }; struct AppleConsumer { }; struct MeatConsumer { }; struct ShillyShallyProducer : public Producer<AppleConsumer>, public Producer<MeatConsumer> { }; int _tmain(int argc, _TCHAR* argv[]) { ShillyShallyProducer producer; AppleConsumer consumer; producer.SetConsumer(&consumer); // <--- Ambiguous call!! return 0; } This is the compilation error: // error C2385: ambiguous access of 'SetConsumer' // could be the 'SetConsumer' in base 'Producer<AppleConsumer>' // or could be the 'SetConsumer' in base 'Producer<MeatConsumer>' I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer. Why isn't it? I could get around this by changing Producer to template <typename TConsumer> struct Producer { template <typename TConsumer2> void SetConsumer(TConsumer2* consumer) { consumer_ = consumer; } TConsumer* consumer_; }; and call SetConsumer as producer.SetConsumer<AppleConsumer>(&consumer); // Unambiguous call!! but it would be nicer if I didn't have to...

    Read the article

  • Function signature-like expressions as C++ template arguments

    - by Jeff Lee
    I was looking at Don Clugston's FastDelegate mini-library and noticed a weird syntactical trick with the following structure: TemplateClass< void( int, int ) > Object; It almost appears as if a function signature is being used as an argument to a template instance declaration. This technique (whose presence in FastDelegate is apparently due to one Jody Hagins) was used to simplify the declaration of template instances with a semi-arbitrary number of template parameters. To wit, it allowed this something like the following: // A template with one parameter template<typename _T1> struct Object1 { _T1 m_member1; }; // A template with two parameters template<typename _T1, typename _T2> struct Object2 { _T1 m_member1; _T2 m_member2; }; // A forward declaration template<typename _Signature> struct Object; // Some derived types using "function signature"-style template parameters template<typename _Dummy, typename _T1> struct Object<_Dummy(_T1)> : public Object1<_T1> {}; template<typename _Dummy, typename _T1, typename _T2> struct Object<_Dummy(_T1, _T2)> : public Object2<_T1, _T2> {}; // A. "Vanilla" object declarations Object1<int> IntObjectA; Object2<int, char> IntCharObjectA; // B. Nifty, but equivalent, object declarations typedef void UnusedType; Object< UnusedType(int) > IntObjectB; Object< UnusedType(int, char) > IntCharObjectB; // C. Even niftier, and still equivalent, object declarations #define DeclareObject( ... ) Object< UnusedType( __VA_ARGS__ ) > DeclareObject( int ) IntObjectC; DeclareObject( int, char ) IntCharObjectC; Despite the real whiff of hackiness, I find this kind of spoofy emulation of variadic template arguments to be pretty mind-blowing. The real meat of this trick seems to be the fact that I can pass textual constructs like "Type1(Type2, Type3)" as arguments to templates. So here are my questions: How exactly does the compiler interpret this construct? Is it a function signature? Or, is it just a text pattern with parentheses in it? If the former, then does this imply that any arbitrary function signature is a valid type as far as the template processor is concerned? A follow-up question would be that since the above code sample is valid code, why doesn't the C++ standard just allow you to do something like the following, which is does not compile? template<typename _T1> struct Object { _T1 m_member1; }; // Note the class identifier is also "Object" template<typename _T1, typename _T2> struct Object { _T1 m_member1; _T2 m_member2; }; Object<int> IntObject; Object<int, char> IntCharObject;

    Read the article

  • Problem in transfering file from server to client using C sockets

    - by coolrockers2007
    I want to ask, why I cannot transfer file from server to client? When I start to send the file from server, the client side program will have problem. So, I spend some times to check the code, But I still cannot find out the problem Can anyone point out the problem for me? CLIENTFILE.C #include stdio.h #include stdlib.h #include time.h #include netinet/in.h #include fcntl.h #include sys/types.h #include string.h #include stdarg.h #define PORT 5678 #define MLEN 1000 int main(int argc, char *argv []) { int sockfd; int number,message; char outbuff[MLEN],inbuff[MLEN]; //char PWD_buffer[_MAX_PATH]; struct sockaddr_in servaddr; FILE *fp; int numbytes; char buf[2048]; if (argc != 2) fprintf(stderr, "error"); if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) fprintf(stderr, "socket error"); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) fprintf(stderr, "connect error"); if ( (fp = fopen("/home/na/nall9047/write.txt", "w")) == NULL){ perror("fopen"); exit(1); } printf("Still NO PROBLEM!\n"); //Receive file from server while(1){ numbytes = read(sockfd, buf, sizeof(buf)); printf("read %d bytes, ", numbytes); if(numbytes == 0){ printf("\n"); break; } numbytes = fwrite(buf, sizeof(char), numbytes, fp); printf("fwrite %d bytes\n", numbytes); } fclose(fp); close(sockfd); return 0; } SERVERFILE.C #include stdio.h #include fcntl.h #include stdlib.h #include time.h #include string.h #include netinet/in.h #include errno.h #include sys/types.h #include sys/socket.h #includ estdarg.h #define PORT 5678 #define MLEN 1000 int main(int argc, char *argv []) { int listenfd, connfd; int number, message, numbytes; int h, i, j, alen; int nread; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; FILE *in_file, *out_file, *fp; char buf[4096]; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) fprintf(stderr,"listen error") ; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) fprintf(stderr,"bind error") ; alen = sizeof(struct sockaddr); connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &alen); if (connfd < 0) fprintf(stderr,"error connecting") ; printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr)); fp = fopen ("/home/na/nall9047/read.txt", "r"); // open file stored in server if (fp == NULL) { printf("\nfile NOT exist"); } //Sending file while(!feof(fp)){ numbytes = fread(buf, sizeof(char), sizeof(buf), fp); printf("fread %d bytes, ", numbytes); numbytes = write(connfd, buf, numbytes); printf("Sending %d bytes\n",numbytes); } fclose (fp); close(listenfd); close(connfd); return 0; }

    Read the article

  • Animation issue caused by C# parameters passed by reference rather than value, but where?

    - by Jordan Roher
    I'm having trouble with sprite animation in XNA that appears to be caused by a struct passed as a reference value. But I'm not using the ref keyword anywhere. I am, admittedly, a C# noob, so there may be some shallow bonehead error in here, but I can't see it. I'm creating 10 ants or bees and animating them as they move across the screen. I have an array of animation structs, and each time I create an ant or bee, I send it the animation array value it requires (just [0] or [1] at this time). Deep inside the animation struct is a timer that is used to change frames. The ant/bee class stores the animation struct as a private variable. What I'm seeing is that each ant or bee uses the same animation struct, the one I thought I was passing in and copying by value. So during Update(), when I advance the animation timer for each ant/bee, the next ant/bee has its animation timer advanced by that small amount. If there's 1 ant on screen, it animates properly. 2 ants, it runs twice as fast, and so on. Obviously, not what I want. Here's an abridged version of the code. How is BerryPicking's ActorAnimationGroupData[] getting shared between the BerryCreatures? class BerryPicking { private ActorAnimationGroupData[] animations; private BerryCreature[] creatures; private Dictionary<string, Texture2D> creatureTextures; private const int maxCreatures = 5; public BerryPickingExample() { this.creatures = new BerryCreature[maxCreatures]; this.creatureTextures = new Dictionary<string, Texture2D>(); } public void LoadContent() { // Returns data from an XML file Reader reader = new Reader(); animations = reader.LoadAnimations(); CreateCreatures(); } // This is called from another function I'm not including because it's not relevant to the problem. // In it, I remove any creature that passes outside the viewport by setting its creatures[] spot to null. // Hence the if(creatures[i] == null) test is used to recreate "dead" creatures. Inelegant, I know. private void CreateCreatures() { for (int i = 0; i < creatures.Length; i++) { if (creatures[i] == null) { // In reality, the name selection is randomized creatures[i] = new BerryCreature("ant"); // Load content and texture (which I create elsewhere) creatures[i].LoadContent( FindAnimation(creatures[i].Name), creatureTextures[creatures[i].Name]); } } } private ActorAnimationGroupData FindAnimation(string animationName) { int yourAnimation = -1; for (int i = 0; i < animations.Length; i++) { if (animations[i].name == animationName) { yourAnimation = i; break; } } return animations[yourAnimation]; } public void Update(GameTime gameTime) { for (int i = 0; i < creatures.Length; i++) { creatures[i].Update(gameTime); } } } class Reader { public ActorAnimationGroupData[] LoadAnimations() { ActorAnimationGroupData[] animationGroup; XmlReader file = new XmlTextReader(filename); // Do loading... // Then later file.Close(); return animationGroup; } } class BerryCreature { private ActorAnimation animation; private string name; public BerryCreature(string name) { this.name = name; } public void LoadContent(ActorAnimationGroupData animationData, Texture2D sprite) { animation = new ActorAnimation(animationData); animation.LoadContent(sprite); } public void Update(GameTime gameTime) { animation.Update(gameTime); } } class ActorAnimation { private ActorAnimationGroupData animation; public ActorAnimation(ActorAnimationGroupData animation) { this.animation = animation; } public void LoadContent(Texture2D sprite) { this.sprite = sprite; } public void Update(GameTime gameTime) { animation.Update(gameTime); } } struct ActorAnimationGroupData { // There are lots of other members of this struct, but the timer is the only one I'm worried about. // TimerData is another struct private TimerData timer; public ActorAnimationGroupData() { timer = new TimerData(2); } public void Update(GameTime gameTime) { timer.Update(gameTime); } } struct TimerData { public float currentTime; public float maxTime; public TimerData(float maxTime) { this.currentTime = 0; this.maxTime = maxTime; } public void Update(GameTime gameTime) { currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; if (currentTime >= maxTime) { currentTime = maxTime; } } }

    Read the article

  • Please help - sorting integers in structs

    - by maja k.
    I have a struct like this: struct db { string name,sur; int num; }; And declared an array of db structs: struct db a[10]; and every member of a[] is filled with a name, surname and a number but there can be the same number appearing multiple times. I need to sort the numbers, and print the results, i.e. sort by the num of each struct and the print the name, sur and the num in each line starting from the smallest num going down to the largest. I don't know how to do this, please help me.

    Read the article

  • Why is partial specialziation of a nested class template allowed, while complete isn't?

    - by drhirsch
    template<int x> struct A { template<int y> struct B {};. template<int y, int unused> struct C {}; }; template<int x> template<> struct A<x>::B<x> {}; // error: enclosing class templates are not explicitly specialized template<int x> template<int unused> struct A<x>::C<x, unused> {}; // ok So why is the explicit specialization of a inner, nested class (or function) not allowed, if the outer class isn't specialiced too? Strange enough, I can work around this behaviour if I only partially specialize the inner class with simply adding a dummy template parameter. Makes things uglier and more complex, but it works. Note: I need this feature for recursive templates of the inner class for a set of the outer class. To make things even more complicate, in reality I only need a template function instead of the inner class. But partial specialization of functions is generally disallowed somewhere else in the standard ^^

    Read the article

  • Decode JSON with mochijson2 in Erlang

    - by Jon Romero
    I have a var that has some JSON data: A = <<"{\"job\": {\"id\": \"1\"}}">>. Using mochijson2, I decode the data: Struct = mochijson2:decode(A). And now I have this: {struct,[{<<"job">>,{struct,[{<<"id">>,<<"1">>}]}}]} I am trying to read (for example), "job" or "id". I tried using struct.get_value but it doesn't seem to work. Any ideas?

    Read the article

  • user defined Copy ctor, and copy-ctors further down the chain - compiler bug ? programmers brainbug

    - by J.Colmsee
    Hi. i have a little problem, and I am not sure if it's a compiler bug, or stupidity on my side. I have this struct : struct BulletFXData { int time_next_fx_counter; int next_fx_steps; Particle particles[2];//this is the interesting one ParticleManager::ParticleId particle_id[2]; }; The member "Particle particles[2]" has a self-made kind of smart-ptr in it (resource-counted texture-class). this smart-pointer has a default constructor, that initializes to the ptr to 0 (but that is not important) I also have another struct, containing the BulletFXData struct : struct BulletFX { BulletFXData data; BulletFXRenderFunPtr render_fun_ptr; BulletFXUpdateFunPtr update_fun_ptr; BulletFXExplosionFunPtr explode_fun_ptr; BulletFXLifetimeOverFunPtr lifetime_over_fun_ptr; BulletFX( BulletFXData data, BulletFXRenderFunPtr render_fun_ptr, BulletFXUpdateFunPtr update_fun_ptr, BulletFXExplosionFunPtr explode_fun_ptr, BulletFXLifetimeOverFunPtr lifetime_over_fun_ptr) :data(data), render_fun_ptr(render_fun_ptr), update_fun_ptr(update_fun_ptr), explode_fun_ptr(explode_fun_ptr), lifetime_over_fun_ptr(lifetime_over_fun_ptr) { } /* //USER DEFINED copy-ctor. if it's defined things go crazy BulletFX(const BulletFX& rhs) :data(data),//this line of code seems to do a plain memory-copy without calling the right ctors render_fun_ptr(render_fun_ptr), update_fun_ptr(update_fun_ptr), explode_fun_ptr(explode_fun_ptr), lifetime_over_fun_ptr(lifetime_over_fun_ptr) { } */ }; If i use the user-defined copy-ctor my smart-pointer class goes crazy, and it seems that calling the CopyCtor / assignment operator aren't called as they should. So - does this all make sense ? it seems as if my own copy-ctor of struct BulletFX should do exactly what the compiler-generated would, but it seems to forget to call the right constructors down the chain. compiler bug ? me being stupid ? Sorry about the big code, some small example could have illustrated too. but often you guys ask for the real code, so well - here it is :D EDIT : more info : typedef ParticleId unsigned int; Particle has no user defined copyctor, but has a member of type : Particle { .... Resource<Texture> tex_res; ... } Resource is a smart-pointer class, and has all ctor's defined (also asignment operator) and it seems that Resource is copied bitwise. EDIT : henrik solved it... data(data) is stupid of course ! it should of course be rhs.data !!! sorry for huge amount of code, with a very little bug in it !!! (Guess you shouldn't code at 1 in the morning :D )

    Read the article

  • C++ Linux getpeername IP family

    - by gln
    hi In my Linux C++ application I'm using getpeername in order to get the peer IP. my problem is: when I enable the IPv6 on my machine the IP I got from the peer is with family IF_INET6 although it is IPv4. code: int GetSockPeerIP( int sock) { struct sockaddr_storage ss; struct socklen_t salen = sizeof(ss); struct sockaddr *sa; memset(&ss,0,salen); sa = (sockaddr *)&ss; if(getpeername(sock,sa,&salen) != 0) { return -1; } char * ip=NULL: if(sa->sa_family == AF_INET) { ip = inet_ntoa((struct sockaddr_in *)sa)->sin_addr); } else { //ip = how to convert IPv6 to char IP? } return 0; } how can I fix it? thanks1

    Read the article

  • What happens when value types are created?

    - by Bob
    I'm developing a game using XNA and C# and was attempting to avoid calling new struct() type code each frame as I thought it would freak the GC out. "But wait," I said to myself, "struct is a value type. The GC shouldn't get called then, right?" Well, that's why I'm asking here. I only have a very vague idea of what happens to value types. If I create a new struct within a function call, is the struct being created on the stack? Will it simply get pushed and popped and performance not take a hit? Further, would there be some memory limit or performance implications if, say, I need to create many instances in a single call? Take, for instance, this code: spriteBatch.Draw(tex, new Rectangle(x, y, width, height), Color.White); Rectangle in this case is a struct. What happens when that new Rectangle is created? What are the implications of having to repeat that line many times (say, thousands of times)? Is this Rectangle created, a copy sent to the Draw method, and then discarded (meaning no memory getting eaten up the more Draw is called in that manner in the same function)? P.S. I know this may be pre-mature optimization, but I'm mostly curious and wish to have a better understanding of what is happening.

    Read the article

  • How to overwrite an array of char pointers with a larger list of char pointers?

    - by Casey
    My function is being passed a struct containing, among other things, a NULL terminated array of pointers to words making up a command with arguments. I'm performing a glob match on the list of arguments, to expand them into a full list of files, then I want to replace the passed argument array with the new expanded one. The globbing is working fine, that is, g.gl_pathv is populated with the list of expected files. However, I am having trouble copying this array into the struct I was given. #include <glob.h> struct command { char **argv; // other fields... } void myFunction( struct command * cmd ) { char **p = cmd->argv; char* program = *p++; // save the program name (e.g 'ls', and increment to the first argument glob_t g; memset(&g, 0, sizeof(g)); g.gl_offs = 1; int res = glob(*p++, GLOB_DOOFFS, NULL, &g); glob_handle_res(res); while (*p) { res = glob(*p, GLOB_DOOFFS | GLOB_APPEND, NULL, &g); glob_handle_res(res); } if( g.gl_pathc <= 0 ) { globfree(&g); } cmd->argv = malloc((g.gl_pathc + g.gl_offs) * sizeof *cmd->argv); if (cmd->argv == NULL) { sys_fatal_error("pattern_expand: malloc failed\n");} // copy over the arguments size_t i = g.gl_offs; for (; i < g.gl_pathc + g.gl_offs; ++i) cmd->argv[i] = strdup(g.gl_pathv[i]); // insert the original program name cmd->argv[0] = strdup(program); ** cmd->argv[g.gl_pathc + g.gl_offs] = 0; ** globfree(&g); } void command_free(struct esh_command * cmd) { char ** p = cmd->argv; while (*p) { free(*p++); // Segfaults here, was it already freed? } free(cmd->argv); free(cmd); } Edit 1: Also, I realized I need to stick program back in there as cmd-argv[0] Edit 2: Added call to calloc Edit 3: Edit mem management with tips from Alok Edit 4: More tips from alok Edit 5: Almost working.. the app segfaults when freeing the command struct Finally: Seems like I was missing the terminating NULL, so adding the line: cmd->argv[g.gl_pathc + g.gl_offs] = 0; seemed to make it work.

    Read the article

  • Using OpenGL vertex buffers in C++.

    - by Ren
    I've loaded a Wavefront .obj file and drawn it in immediate mode, and it works fine. I'm now trying to draw the same model with a vertex buffer, but I have a question. My model data is organized in the following structures: struct Vert { double x; double y; double z; }; struct Norm { double x; double y; double z; }; struct Texcoord { double u; double v; double w; }; struct Face { unsigned int v[3]; unsigned int n[3]; unsigned int t[3]; }; struct Model { unsigned int vertNumber; unsigned int normNumber; unsigned int texcoordNumber; unsigned int faceNumber; Vert * vertArray; Norm * normArray; Texcoord * texcoordArray; Face * faceArray; }; As it is now, I don't think there is any redundant data, since multiple face structures can point to the same vertex, normal, or texture coordinate. When I make vbo's for the vertex positions, normals, and texture coordinates, and assign data to them with glBufferData, do I have to have make arrays with redundant data so that they will all have the same number of elements in the same order? I'd like to know if there is a simpler way to fill the buffers with the way I already have the model's data organized.

    Read the article

  • Using netlink to obtain arp entries only returns stale entries

    - by Ben
    I'm currently trying to retrieve reachable neighbors from the arp table in a user space program written in c. I've looked through the source code to the "ip neigh" command (ipneigh.c) and it appears that I should use the flag NUD_REACHABLE. struct { struct nlmsghdr n; struct ndmsg r; } req; memset(&req, 0, sizeof(req)); req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg)); req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT; req.n.nlmsg_type = RTM_GETNEIGH; req.r.ndm_state = NUD_REACHABLE; However, when I look at the data returned from the kernel, I only have stale entries. In fact, no matter what I put for req.r.ndm_state it seems to return only entries marked as stale by ip neigh. The remainder of my code is modeled after this example: http://linux-hacks.blogspot.com/2009/01/sample-code-to-learn-netlink.html

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >