Closed. This question is off-topic. It is not currently accepting answers. Learn more。
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
去年关门了。
我在寻找是否有可能在C中扩大数组大小而不丢失旧值,这就是我猜Python中的append函数。
你看到这两个调用的最后参数有什么不同吗?因为当重新分配时,会将数组缩小到两个字节,所以数组内容会丢失,行为会变得稍微不确定。
给
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
去年关门了。
我在寻找是否有可能在C中扩大数组大小而不丢失旧值,这就是我猜Python中的append函数。
int size_arr = 1;
int *arr = (int *)malloc(sizeof(int)*size_arr);
// Let's give first element of arr to 1
*(arr+0) = 1;
size_arr++;
//Realloc, but I lost *(arr+0) = 1
arr = (int *)realloc(arr, size_arr);
最佳答案
只需比较两行代码:
int *arr = (int *)malloc(sizeof(int)*size_arr);
arr = (int *)realloc(arr, size_arr);
你看到这两个调用的最后参数有什么不同吗?因为当重新分配时,会将数组缩小到两个字节,所以数组内容会丢失,行为会变得稍微不确定。
给
realloc
一个合适的大小,你就会看到它保留了你的原始数据。关于c - 如何追加数组? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49741621/