I have a struct as follows, with a pointer to a function called "length" that will return the length of the chars member.
typedef struct pstring_t {
char * chars;
int (* length)();
} PString;
I have a function to return the length of the characters from a pointer to a PString:
int length(PString * self) {
return strlen(self->chars);
}
I have a function initializeString() that returns a pointer to a PString:
PString * initializeString() {
PString *str;
str->length = &length;
return str;
}
It is clear that I am doing something very wrong with my pointers here, because the str->length = &length
line causes an EXC_BAD_ACCESS signal in my debugger, as does `return strlen(self->chars). Does anyone have any insights into this problem?
I specifically want to be able have the initializeString() function return a pointer to a PString, and the length function to use a pointer to a PString as input. This is just an experiment in implementing a rudimentary object-oriented system in C, but I don't have a lot of experience dealing with pointers head-on. Thanks for any help you can give me.