title: Function pointer as a member of a C struct
body: <p>I have a struct as follows, with a pointer to a function called "length" that will return the length of the chars member.</p>
  
  <pre><code>typedef struct pstring_t {
      char * chars;
      int (* length)();
  } PString;
  </code></pre>
  
  <p>I have a function to return the length of the characters from a pointer to a PString:</p>
  
  <pre><code>int length(PString * self) {
      return strlen(self-&gt;chars);
  }
  </code></pre>
  
  <p>I have a function initializeString() that returns a pointer to a PString:</p>
  
  <pre><code>PString * initializeString() {
      PString *str;
      str-&gt;length = &amp;length;
      return str;
  }
  </code></pre>
  
  <p>It is clear that I am doing something very wrong with my pointers here, because the <code>str-&gt;length = &amp;length</code> line causes an EXC_BAD_ACCESS signal in my debugger, as does `return strlen(self->chars). Does anyone have any insights into this problem?</p>
  
  <p>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.</p>