data structures - Using Pointer to Functions Inside Structs in C -


just s & g. wanted build own library in c. wanted make follow c# object notion , realized way have base types use pointers functions members.

well, stuck , have no clue why. following sample of string base type may like:

#ifndef string_h #define string_h  typedef struct _string {     char* value;     int length;     string* (*trim)(string*, char);  } string;  string* string_allocate(char* s); string* trim(string* s, char trimcharacter);  #endif  /* string_h */ 

and implementation:

string* trim(string* s, char trimcharacter) {     int i=0;     for(i=0; i<s->length; i++)     {         if( s->value[i] == trimcharacter )         {             char* newvalue = (char *)malloc(sizeof(char) * (s->length - 1));             int j=1;              for(j=1; j<s->length; j++)             {                 newvalue[j] = s->value[j];             }              s->value = newvalue;         }         else         {             break;         }     }      s->length = strlen(s->value);     return s; }  string* string_allocate(char* s) {     string* newstring = (string *)malloc(sizeof(string));     newstring->value = malloc(strlen(s) + 1);     newstring->length = strlen(s) + 1;     strcpy(newstring->value, s);      newstring->trim = trim; } 

however when compiling in netbeans (for c, c++) following error:

in file included string.c:6: string.h:8: error: expected specifier-qualifier-list before ‘string’ string.c: in function ‘string_allocate’: string.c:43: error: ‘string’ has no member named ‘trim’ make[2]: *** [build/debug/gnu-linux-x86/string.o] error 1 make[1]: *** [.build-conf] error 2 make: *** [.build-impl] error 2  build failed (exit value 2, total time: 77ms) 

can me understand how come string->trim member non-existent and/or how fix this?

thank you

with recursive structure need write

typedef struct _string string; 

before define struct, or else internally have string replace struct _string (just until typedef comes scope).


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -