Sal*_*kes 3 c arrays malloc struct pointers
我需要在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);
}
Run Code Online (Sandbox Code Playgroud)
程序编译并运行,整数赋值似乎工作正常.但是,该阵列不能正常工作.
有什么建议?我想米仍然是一个指针(传递给功能等).
谢谢.
这是你的问题:
scanf("Enter array size: %d",&(m->N));
Run Code Online (Sandbox Code Playgroud)
它应该是两个单独的步骤:
printf("Enter array size: ");
scanf("%d",&(m->N));
Run Code Online (Sandbox Code Playgroud)
(以及调试检查:)
printf("The size entered appears to be %d\n", m->N);
Run Code Online (Sandbox Code Playgroud)
那样,你知道你是否得到了你想要获得的价值!