简体   繁体   English

在struct中为数组分配内存(在C中)

[英]Allocating memory for array in struct (in C)

I need to define a type-struct in C that contains an array to be malloc'd as: 我需要在C中定义一个包含要被malloc为的数组的类型结构:

#include <stdio.h>
#include <stdlib.h>

typedef struct mine
{
    int N;
    double *A;
} mine;

int main(int argc, char** argv) 
{
    int i;
    mine *m=malloc(sizeof(mine));
    printf("sizeof(mine)=%d\n",sizeof(mine));
    scanf("Enter array size: %d",&(m->N));
    m->A=malloc((m->N)*sizeof(double));
    for(i=0; i < m->N; i++)
        m->A[i]=i+0.23;
    printf("First array element: %lf",m->A[0]);

    return (EXIT_SUCCESS);
}

The program compiles and runs, and the integer assignment seems to work fine. 程序编译并运行,整数赋值似乎工作正常。 The array is not working as it should, however. 但是,该阵列不能正常工作。

Any suggestions? 有什么建议么? I would like m to remain a pointer (to pass to functions etc.). 我想仍然是一个指针(传递给功能等)。

Thanks. 谢谢。

This is your problem: 这是你的问题:

scanf("Enter array size: %d",&(m->N));

It should be two separate steps: 它应该是两个单独的步骤:

printf("Enter array size: ");
scanf("%d",&(m->N));

(and for debugging checking:) (以及调试检查:)

printf("The size entered appears to be %d\n", m->N);

That way, you know if you got the value you intended to get! 那样,你知道你是否得到了你想要获得的价值!

如果@abelenky回答你的问题很好,但我总是被告知要从void *中投出malloc的结果,它会返回到你实际使用的任何东西。

mine *m = (mine *)malloc(sizeof(mine));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM