Can a loop cause issues with assignment in C

穿精又带淫゛_ 提交于 2019-12-11 22:55:34

问题


(This is related to a previous issue I had.) In trying to assign values from one character array to another, I'm facing a weird problem where the correct values aren't being copied but only when I use a loop. I commented out the loop and wrote out its iterations manually and it worked as I wanted it to. What could be causing this issue?

//Causes incorrect data transfer

 for(int q=0; q<4; q++){


   directory[q] = malloc(sizeof(char) * (1 + strlen(temp[q])));

   strcpy(directory[q],temp[q]);


  }

//But this works as it should

directory[0] = malloc(sizeof(char) * (1 + strlen(temp[0])));

strcpy(directory[0], temp[0]);

directory[1] = malloc(sizeof(char) * (1 + strlen(temp[1])));

strcpy(directory[1], temp[1]);

directory[2] = malloc(sizeof(char) * (1 + strlen(temp[2])));

strcpy(directory[2], temp[2]);

directory[3] = malloc(sizeof(char) * (1 + strlen(temp[3])));

strcpy(directory[3], temp[3]);

来源:https://stackoverflow.com/questions/12984743/can-a-loop-cause-issues-with-assignment-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!