trouble with pointers
OK once again, pointers are causing me headaches
I'm trying to get a word from a file, and write that into a buffer. The buffer is malloced like so:
and the function called:
char *buf = malloc( INIT * sizeof(char) );
where getword has the definition:
while ( getword(buf, INIT) != EOF )
Then the buffer is realloced inside the getword function, if necessary.
getword(char *W, int size)
The problem is, if the realloc is done, the W returned is correct, but the buf recieved is junk. I assumed that by reallocing W, i was reallocing the same pointer as buf. Is this not correct?
size *= 2;
W = realloc(W, size * sizeof(char) );
A pointer lets you change what it points to. Thus, if it's a pointer you need to change, you need a pointer to that pointer.
If the memory pointed to by buf is realloc'ed within the getword function, then the buf argument must be passed as a pointer to a pointer.
Like quzah said.[/edit]
int getword(char **W, int size)
// Resize/repoint the argument to a new larger memory area
*W = realloc(*W,new_even_bigger_size);
// Initial malloc call
char * buf = malloc(INIT);
// Call getword function... afterwards, buf points to new address
cool thanks, that worked :)