指针传递给函数

时间:2014-04-14 09:09:13

标签: c windows mingw-w64

当我使用这段代码时,不是直接从init()调用malloc(),而是在Windows 8下显示错误消息。 标准信息“程序......停止工作”。

我的一些程序在Windows 8下生成相同的内容。在Linux下,一切都很好。 win8的C语言不兼容ANSI吗?

FILE *dumpfile;
double *cx;
void init_var(double *ptr) {
    ptr = malloc (L*sizeof(double));
    for (i=0; i<L; i++) ptr[i] = (double) i;
}

void init() {
//    cx = malloc (L*sizeof(double));
//    for (i=0; i<L; i++) cx[i] = i;
    init_var(cx);
    dumpfile = fopen( "dump.txt", "w" );
}

UPD。 Aaaaargh。我现在明白了。

1 个答案:

答案 0 :(得分:1)

您正在函数内部重新分配函数参数,但这并不会更改调用者上下文中的参数。这是因为C是按值调用

您必须通过init_var() cx地址才能更改它:

void init_var(double **ptr)
{
  *ptr = malloc(L * sizeof **ptr);
  /* ... */
}

void init(void)
{
  init_var(&cx);
}
相关问题