I come from the Java world and have developed a penchant towards C lately. I was going through the chapter on pointers in K&R and there's an example wherein the authors input N lines in an array of pointers and then sorts it. Here's my readLines(..)
method:
void readlines(char *lines[]) {
/*read 5 lines*/
for(int i = 0; i < 5; i++) {
char line[MAXLENGTH];
printf("%p\n",line);
readNewLine(line,MAXLENGTH);
/*make the ith pointer in the array point to this line*/
*(lines + i) = line;
}
}
What I have tried to do here is input 5 lines into lines
. For each line (i
), I get some space, print its address (for debugging) and then read a line into that space. Then I make the ith
pointer point to the start of that memory location. When I run the program, I see the same virtual memory address. Shouldn't a new memory space be allocated with each loop on the heap with line
pointing to it? Why do I see the same address then?
Also, K&R's solution is much more complicated and elegant. My version seems just too simple. What is it that I am missing here?
Edit:
Here's the caller:
int main(int argc, char *argv[]) {
char *lines[5];
readlines(lines);
//print all the input lines
for(int i = 0; i < 5; i++) {
char *line = lines[i];
while(*line) {
printf("%c",*line);
line++;
}
}
return 0;
}
This prints the last line that I entered. Now as mentioned in the comments, the buffer in the callee is allocated on the stack, which should be destroyed once the function returns. Where is the last line getting stored then?