// 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
c语言,关于pointer array的问题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- CSDN专家-link 2021-10-12 05:18关注
因为你所有的arr数组元素都指向temp这个数组,当然一样了。temp最后被赋值为ee,叫以全是ee
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 C++ yoloV5改写遇到的问题
- ¥20 win11修改中文用户名路径
- ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
- ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
- ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
- ¥15 帮我写一个c++工程
- ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
- ¥15 关于smbclient 库的使用
- ¥15 微信小程序协议怎么写
- ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?