我已经使用 java 很长时间了,但由于某种原因,我需要使用 C(ANSI C 而不是 C++)来编写一个简单的代码。我需要将指针从外部传递给函数,为指针分配一些内存并在函数返回之前分配一些值。我有我的代码
#include <stdio.h>
#include <stdlib.h>
void test(int *a)
{
int n=3;
// I have to call another function t determine the size of the array
n = estimatesize(); // n >=3
// I tried fix size n=10 also
a = (int*)malloc(n*sizeof(int));
a[0] = 1;
a[1] = 2;
a[2] = 3;
}
void main(void)
{
int *s=NULL;
test(s);
printf("%d %d %d", s[0], s[1], s[2]);
}
我不知道为什么代码会崩溃。我一开始以为是estimatesize() 返回了错误的数字,但即使我将n 修复为10,错误仍然存在。所以我不能将指针传递给函数进行内存分配?如果是这样,我如何在函数内部动态创建内存并将其传递出去?我知道这可能是一个安全的问题,但我只想知道这是否可能以及如何做到这一点。谢谢。