如何在函数内部为数组分配内存 [英] How can I allocate memory for array inside a function
问题描述
我正在尝试从用户那里收到一个电话号码. 并在函数内创建一个具有该数字的数组. 这是我的一些尝试,我遇到了运行时错误. 非常感谢您的帮助.
I am trying to receive a number from the user. And create an array with that number, but, inside a function. Here are my few attempts, I get into run time errors. Help is very much appreciated.
#include <stdio.h>
#include <stdlib.h>
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 **
.您要么传递一个指向该指针的指针,然后将分配的内存存储在其中:
You have done well upto the point you understood you need to pass a pointer to pointer. But your function signature doesn't take an int **
. Either you pass a pointer to pointer and store the allocated memory in it:
void Init(int **pp, int num)
{
int *p;
p = malloc(num*sizeof(int));
if (!p)
{
printf("Cannot allocate memory\n");
}
*pp = p;
}
并检查Init()
是否返回正确的指针:
And check if the Init()
returns a proper pointer:
Init(&p, num);
if(p == NULL) {
/*Memory allocation failed */
}
或分配内存并返回指针:
Or allocate memory and return the pointer:
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()
的原型.
Change the prototype of Init()
accordingly.
在任何情况下,都不能在Init()
中使用free()
指针.这只会立即取消分配内存,您将剩下一个 悬挂指针 .
In any case, you must not free()
the pointer in Init()
. That just de-allocates memory immediately and you'll be left with a dangling pointer.
完成后,您需要在main()
中的free()
.
And you need to free()
in the main()
after you are done with it.
这篇关于如何在函数内部为数组分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!