[英]Coding in C, Why are my array values changing?
I'm using GDB to go through my code and each time the while loop is entered, the values in NameList[] change. 我正在使用GDB遍历代码,每次进入while循环时,NameList []中的值都会更改。 Like I set NameList[0] to chr2, but when I go back through the while loop in gdb, I say x/s NameList[0] and now it's set to the new value of chr2!
就像我将NameList [0]设置为chr2一样,但是当我回到gdb中的while循环时,我说x / s NameList [0],现在将其设置为chr2的新值! How is this able to happen?
这怎么可能发生? I know I'm changing the pointer, but shouldn't the array be storing the old value of the pointer and not be allowed to update?
我知道我正在更改指针,但是数组不应该存储指针的旧值并且不允许更新吗?
while (fgets(thisline, length, input) != NULL) {
chr = strtok(Line, " ");
if(chr != NULL) {
chr2 = strtok(chr, " ")
int j = 0;
while(NameList[j] != NULL) {
j++;
}
NameList[j] = chr2;
}
}
Try changing 尝试改变
NameList[j] = chr2;
to 至
NameList[j] = strdup(chr2);
And see what happens. 看看会发生什么。 The issue is that you are just storing a pointer to the char array, and that char array is changing out from under you.
问题是您只存储了一个指向char数组的指针,而char数组正在从您的下方改变。 The strdup function copies the whole array.
strdup函数复制整个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.