// in test.txt file
//aa bb cc
//dd ee
int main(){
FILE *fp = fopen("test.txt", "r");
char *data;
fseek(fp,0L,2);
int size = ftell(fp);
data = (char *)malloc(sizeof(char)*size);
rewind(fp);
fread(data,sizeof(char),size,fp);
printf("%s",data); //data store all element from file, here is correct output from
//test.txt
int total=0, index;
for(index = 0; index < strlen(data); index++){
if(data[index] == ' ' || data[index] == '\n'){
total++;
}
}
printf("total=%d\n", total);
char *arr[total];
int i,j;
char temp[8];
int count = 0;
//following nested for loops are trying to store a string as an single char pointer
//to pointer array arr from data
for(i = 0; i<total; i++){
for(j = 0; j<strlen(data); j++){
//temp expected to store "aa" "bb" "cc" etc before WS and '\n'
temp[count] = data[j];
count++;
if(data[j] == ' ' || data[j] == '\n'){
arr[i] = temp;
count = 0;
}
}
}
// expecte output are "aa", "bb", "cc", "dd", "ee"
//but all elements are "ee", why?
printf("%s\n", arr[0]);
printf("%s\n", arr[1]);
printf("%s\n", arr[2]);
printf("%s\n", arr[3]);
printf("%s\n", arr[4]);
return 0;
}
//any help would be appreciated.
```c
因为你所有的arr数组元素都指向temp这个数组,当然一样了。temp最后被赋值为ee,叫以全是ee