kassc 2021-10-12 04: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-12 05:18
    关注

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

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

报告相同问题?

问题事件

  • 系统已结题 10月21日
  • 已采纳回答 10月13日
  • 创建了问题 10月12日

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么