我不确定我是否正确使用了 realloc 函数。
在我的程序中,我首先询问用户数组的大小并使用 malloc 为其分配内存,然后用一些值对其进行初始化。
然后我想使用 realloc 将同一个数组的大小扩大两倍。这是我的代码。我是否使用 realloc 来正确调整 int *A 的大小?
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
printf("Enter size of array\n");
scanf("%d", &n);
int *A = (int*)malloc(n*sizeof(int)); //dynamically allocated array
for (int i = 0; i < n; i++) //assign values to allocated memory
{
A[i] = i + 1;
}
A = (int*)realloc(A, 2*sizeof(int)); //make the array twice the size
free(A);
}
最佳答案
- 使用
malloc()
时,不要强制转换返回值as said here - 您没有使用正确的尺码。在这里
int *A = (int*)malloc(n*sizeof(int));
给malloc
的大小是n*sizeof(int)
。如果你想要两倍的大小,你应该用n*sizeof(int)*2
而不是2*sizeof(int)
调用realloc()
> - 处理
realloc()
失败。如果realloc(A, new_size)
失败,A == NULL
并且您将发生内存泄漏。因此,使用不同的指针B
,检查if (B != NULL)
,然后分配A = B
(old_size = new_size)。如果B == NULL
处理分配失败
关于c - 在运行时使用 realloc 将数组大小加倍。我的代码正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44224107/