0

我已经使用 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,错误仍然存​​在。所以我不能将指针传递给函数进行内存分配?如果是这样,我如何在函数内部动态创建内存并将其传递出去?我知道这可能是一个安全的问题,但我只想知道这是否可能以及如何做到这一点。谢谢。

4

1 回答 1

2

有两种解决方案:要么从函数返回指针,要么通过引用传递参数。

对于第一个,您根本不接受任何参数,而是返回指针:

int *test(void)
{
    int *a = malloc(...);
    ...
    return a;
}

int main(void)
{
    int *s = test();
    ...
}

对于第二个,您需要使用 address-of 运算符传递指针的地址,也就是指向指针的指针&

void test(int **a)
{
    *a = malloc(sizeof(int) * 3);

    for (int i = 0; i < 3; ++i)
        (*a)[i] = i;
}

int main(void)
{
    int *s;
    test(&s);
    ...
}

它现在不起作用的原因是因为指针(sin main)是通过复制它来传递的。所以函数test有一个本地副本,其范围仅在test函数中。a一旦函数返回,对函数的任何更改test都将丢失。正如为参数复制的那样s,这意味着永远不会真正改变值,它仍然在函数调用之后。smainNULL

于 2013-11-04T06:24:21.500 回答