-
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:
Code:
char *buf = malloc( INIT * sizeof(char) );
and the function called:
Code:
while ( getword(buf, INIT) != EOF )
where getword has the definition:
Code:
int
getword(char *W, int size)
Then the buffer is realloced inside the getword function, if necessary.
Code:
size *= 2;
W = realloc(W, size * sizeof(char) );
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?
-
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.
Quzah.
-
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.
[edit]Like quzah said.[/edit]
Code:
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
getword(&buf,INIT);
-
cool thanks, that worked :)