kassc 2021-10-11 20:48 采纳率: 100%
浏览 40
已结题

c语言,关于pointer array的问题

// 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


展开全部

  • 写回答

1条回答 默认 最新

  • CSDN专家-link 2021-10-11 21:18
    关注

    因为你所有的arr数组元素都指向temp这个数组,当然一样了。temp最后被赋值为ee,叫以全是ee

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

问题事件

  • 系统已结题 10月20日
  • 已采纳回答 10月13日
  • 创建了问题 10月11日
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部