Reputation: 4037
As an exercise, I have build a simple program that, given a text file of N
lowercase words and whitespaces, populates a ragged array char *en[N]
.
It works without great problems, apart for one: it populates the ragged array with only the last word of the input.
#include<stdio.h>
#include<ctype.h>
int main(int argc, char *argv[]){
int i = 0, j = 0;
char *en[100];
char temp[20];
FILE *p = fopen(argv[1], "r");
char single;
while((single = fgetc(p)) != EOF){
if(!isspace(single)) /* Temporary store a single word */
temp[i++] = single;
else{
temp[i] = '\0';
en[j++] = temp; /* Save stored word in ragged array */
i = 0;
}
}
printf("%s\n", en[0]); /* Return the same than en[1] and en[99] */
printf("%s\n", en[1]);
printf("%s\n", en[99]);
return 0;
}
I cannot understand why it goes down to the end of the input file. I am unable of detecting major issues that could suggest a wrong approach.
Edit:
The reasoning behind my approach was that an array of *char
can be initialized with this form:
p[0] = "abc";
reasoning that I wrongly tried to translate in the error above, that @coderredoc brilliantly caught. As far as the dimensions of single words and inputs are concerned, I admit I did not put many attention in them. The exercise is centered on a different topic. In any case, thanks a lot your your valuable suggestions!
Upvotes: 1
Views: 59
Reputation: 30926
Your array of charcaters are all pointing to the same char array and then the content of the array at last changes to the last word. And you get only the last word.
A possible solution
en[j++] = temp;
to
en[j++] = strdup(temp);
Then you will achieve the behavior you want your program to have.
Upvotes: 4
Reputation: 44838
You just found out the awesomeness of pointers, congratulations!
Seriously, char *en[100]
is an array of pointers. en[j++] = temp;
assigns the pointer to the first value of temp
to a pointer at en[j++]
. And you do this over and over again. No surprise that you end up with an array of pointers, all of which point to the same array temp
, which holds the contents of the last word.
What to learn from this: a pointer merely points to some memory, and no memory copying happens when you do en[j++] = temp;
. You have to allocate the memory yourself and copy temp
to that new memory yourself.
Upvotes: 2