[英]Pointer value changing unexpectedly when passed to function
So I'm trying to implement an arrayList in C but I'm getting some errors.所以我试图在 C 中实现 arrayList 但我遇到了一些错误。 When i is 4 in the for loop in the main function, insertArrayList is called to insert the number 4. After inserting 4 into my contents array, the first 5 elements of my array are 0,1,2,3,4.当 i 在主 function 中的 for 循环中为 4 时,调用 insertArrayList 插入数字 4。将 4 插入到我的内容数组中后,我的数组的前 5 个元素是 0、1、2、3、4。 But then after my call to PrintArray, the first element in my array changes 6422016. I can not figure out why this is happening.但是在我调用 PrintArray 之后,我数组中的第一个元素更改为 6422016。我不知道为什么会这样。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks.谢谢。
#include <stdlib.h>
#include <math.h>
struct ArrayList{
int numItemsInserted;
int size;
int *contents;
};
void initializeArrayList(struct ArrayList *a, int size){
(*a).numItemsInserted= floor(size / 2);
(*a).size = size;
(*a).contents = malloc(sizeof(int) * size);
}
void PrintArray(struct ArrayList *a){
for (int i = 0 ; i < (*a).numItemsInserted; i++){
printf("%i ", (*a).contents[i]);
}
printf("\n");
}
struct ArrayList insertArrayList(struct ArrayList *a, int num){
if((*a).numItemsInserted == (*a).size){
int newContents[(*a).size * 2];
for (int i = 0; i < (*a).size; i++){
newContents[i] = (*a).contents[i];
}
(*a).contents = newContents;
(*a).size *= 2;
}
(*a).contents[(*a).numItemsInserted] = num;
(*a).numItemsInserted += 1;
PrintArray(a);
}
int main() {
struct ArrayList a1;
initializeArrayList(&a1, 1);
for (int i =0; i < 10; i ++){
if (i == 1){
printf("a");
}
insertArrayList(&a1, i);
}
return 0;
}```
(*a).contents = newContents;
assigns the address of (the first element of) the local array newContents
to (*a).contents
.将本地数组newContents
的(第一个元素)的地址分配给(*a).contents
。 Once ArrayList
returns, newContents
ceases to exist in the C model of computing.一旦ArrayList
返回, newContents
就不再存在于计算的 C model 中。
A proper way to grow an array is to use realloc
to request a larger allocation.增长数组的正确方法是使用realloc
请求更大的分配。 First, request more memory:一、索取更多memory:
int *NewContents = realloc(a->contents, NumberOfElementsDesired * sizeof *NewContents);
Then, test whether the request succeeded or failed:然后,测试请求是成功还是失败:
if (NewContents == NULL)
{
fprintf(stderr, "Error, failed to allocate memory.\n");
exit(EXIT_FAILURE);
}
Then, record the address of the new memory:然后,记录新的memory的地址:
a->contents = NewContents;
After that, fill in the new items.之后,填写新项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.