如何为函数内的数组分配内存

我正在尝试从用户那里收到一个号码。 并创建一个具有该数字的数组,但是在函数内部。 这是我的几次尝试,我遇到了运行时错误。 非常感谢帮助。

#include  #include  int* Init(int* p, int num); int main() { int *p; int num, i; puts("Enter num of grades:"); scanf("%d", &num); Init(&p, num); //for (i = 0; i < num; i++) //{ // scanf("%d", &p[i]); //} free(p); } int* Init(int* p, int num) { int *pp; p = (int *)malloc(num*sizeof(int)); if (!pp) { printf("Cannot allocate memory\n"); return; } p = pp; free(pp); } 

你已经做得很好,你知道你需要将指针传递给指针。 但是你的函数签名不需要int ** 。 您将指针传递给指针并将已分配的内存存储在其中:

 void Init(int **pp, int num) { int *p; p = malloc(num*sizeof(int)); if (!p) { printf("Cannot allocate memory\n"); } *pp = p; } 

并检查Init()返回正确的指针:

  Init(&p, num); if(p == NULL) { /*Memory allocation failed */ } 

或者分配内存并返回指针:

 int* Init(int num) { int *p; p = malloc(num*sizeof(int)); if (!p) { printf("Cannot allocate memory\n"); } return p; } 

main()调用:

 int * p = Init(num); if(p == NULL) { /*Memory allocation failed */ } 

相应地更改Init()的原型。

在任何情况下,您都不能在Init() free()指针。 这只是立即取消分配内存,你将留下一个悬空指针

完成后你需要在main() free()中使用free()

 int *pp; p = (int *)malloc(num*sizeof(int)); if (!pp) /* pp is used uninitialized at this point */ 

 int *p; int num, i; puts("Enter num of grades:"); scanf("%d", &num); Init(&p, num); free(p); /* p is used uninitialized at this point */ 

如果要在另一个函数内为指向int的指针分配空间,则需要将指针传递给指针:

 ... Init(&p, num); ... int Init(int **pp, int num) { *pp = malloc(num * sizeof(int)); ... 

首先,您需要修复函数的原型。 它应该是

 int* Init(int** p, int num); 

然后修复函数定义

 int* Init(int** p, int num) { //int *pp; // You don not need this variable *p = malloc(num*sizeof(int)); // Allocate memory if (!*p) { printf("Cannot allocate memory\n"); return NULL; // Return a NULL pointer } return *p; } 

代码中的一些拼写错误,

 p = (int *)malloc(num * sizeof(int)); 

应该

 pp = (int *)... 

你的free(pp); 是什么导致它不能主要工作,你不想调用它或你分配的内存将不会被保存。 pp的内存在函数调用结束时基本上“丢失”,因为Init p方法参数是一个值复制,不是对mainp版本的精确引用,因此当Init返回时,对p的更改是’丢失’ ”。

简单地做: p = Init(); 并在init return pp;

Exp:这一行p = pp ,将变量p设置为指向pp分配的内存,因此free的pp也是自由的。 我不确定将地址返回到内存总是被认为是好习惯,因为你必须确保它被释放,但对于你的程序它会起作用。