编辑:我大幅更改了我的代码以类似于原始代码的实际结构(我不能发布,因为我必须编写页面和页面来解释一切是什么)。
我一直在努力解决这个问题。我有六个 int 数组 ,ID1
和ID2
, ID3
and array1
, array2
and array3
,其中具有相同索引的名称具有相同的长度(分别为len1
,len2
和len3
)。我的想法是我在 for 循环中重新创建它们,因为这些数组的长度在其中发生了变化。我这样做如下:
/* Before entering the loop, I define these three arrays, where
len1, len2 and len3 are all equal to 100. */
int i,S,len1,len2,len3;
len1=100;
len2=100;
len3=100;
int* ID1;
int* ID2;
int* ID3;
ID1=(int*) malloc((len1)*sizeof(int));
ID2=(int*) malloc((len2)*sizeof(int));
ID3=(int*) malloc((len3)*sizeof(int));
/* Then I fill the arrays with values from a loop which is not relevant
to my problem. Let's just fill them with a simple for loop: */
for(i=0;i<len1;i++){
ID1[i]=i;
ID2[i]=i;
ID3[i]=i;
}
/* Now I enter a loop, in which I create 3 more arrays named array1, array2
and array3: */
for(S=98;S>=0;S--){
printf("ID3[99]:%d (before)\n",ID3[99]); // 1st call to printf
int* array1;
int* array2;
int* array3;
array1=(int*) malloc((len1)*sizeof(int));
array2=(int*) malloc((len2)*sizeof(int));
array3=(int*) malloc((len3)*sizeof(int));
printf("ID3[99]:%d (after)\n",ID3[99]); // 2nd call to printf
/* I do more stuff here. Here len1, len2 and len3 changes, so I have to
re-create the "ID" arrays and the ones named "array". The idea is to fill
the new "ID1", "ID2" and "ID3" arrays with the values of another set of
arrays that I filled with values from complex calculations named
"AnotherArray1", "AnotherArray2" and "AnotherArray3".
The lenghts are always > 100.*/
free(ID1);
free(ID2);
free(ID3);
free(array1);
free(array2);
free(array3);
int* ID1;
int* ID2;
int* ID3;
ID1=(int*) malloc((len1)*sizeof(int));
ID2=(int*) malloc((len2)*sizeof(int));
ID3=(int*) malloc((len3)*sizeof(int));
for(i=0;i<len1;i++){
ID1[i]=AnotherArray1[i];
}
for(i=0;i<len2;i++){
ID2[i]=AnotherArray2[i];
}
for(i=0;i<len3;i++){
ID3[i]=AnotherArray3[i];
}
/* Finally, I need to free the "AnotherArray" arrays, because in the loop
I need to create them again and do some complex calculations with the
"ID" arrays. */
free(AnotherArray1);
free(AnotherArray2);
free(AnotherArray3);
printf("ID3[99]:%d (before, after starting the loop again)\n",ID3[99]); // 3rd call to printf
}
问题是当我这样做时,printf
函数的第 3 次调用与第 1 次和第 2 次调用不同(即,当循环再次开始时,它的某些元素中 ID3 的值突然改变了!)。我真的不知道这里发生了什么......有什么建议吗?如果您需要更多详细信息,请告诉我。