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 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()实现黑框里写入与删除?