C语言 结构体数组的个数如何自己定义?

#include<stdio.h>

void main( )
{
int x;
x=3;
#define N x

struct student
{int num;
char name[20];
char sex;
float weight;
}stu[N];

}
这样为什么不行?
那如果我要N的值通过你所输入的值确定,怎么做?

C99标准出来以前,C语言不支持动态定义数组大小,只能采用动态分配指针方式来完成动态数组的个数定义。如:

struct st {
    int x,y;
    char str[10];
};
struct st *array ;
int n;
printf("input n: "); scanf("%d", &n);
array=(struct st*)malloc(n*sizeof(struct st)); //动态分配n个结构体空间,接下来array的操作,与数组操作是相同的,如:array[0].x=1 ;

C99以后,C语言标准开始支持动态定义数组,但动态数组,在其确定个数之后,在其生命期中,就不可变了。如:

struct st {
    int x,y;
    char str[10];
};
int n;
printf("input n: "); scanf("%d", &n);
struct st array[n] ; //定义动态数组
array[0].x=1 ;

温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-11-21
#define N x 改为#define N 3
就可以

因为数组的个数应该是常量而不是变量
第2个回答  2009-11-21
不用定义结构体数组,定义一个结构体变量,然后再添加元素的时候使用函数malloc.
第3个回答  2009-11-21
C里的数组除了动态分配,必须指明分配大小
#include<stdio.h>

void main( )
{
int x;
x=3;
#define N x

struct student
{int num;
char name[20];
char sex;
float weight;
}*stu;
stu=new student[N];//用指针,动态分配
//stu[0].num;这样调用
}本回答被提问者采纳
第4个回答  2009-11-21
int i;
struct A *a;
scanf("%d",&i);
a = (struct A *)malloc(sizeof(struct A)* i);
相似回答