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

作者&投稿:木终 (若有异议请与网页底部的电邮联系)

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 ;


#define N x 改为#define N 3
就可以

因为数组的个数应该是常量而不是变量

不用定义结构体数组,定义一个结构体变量,然后再添加元素的时候使用函数malloc.

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;这样调用
}

int i;
struct A *a;
scanf("%d",&i);
a = (struct A *)malloc(sizeof(struct A)* i);

C语言如何动态定义结构体数组的元素个数?~

int n;
get(&n); //通过特定方法得到n
struct STUDENT *stu = (struct STUDENT*)malloc(sizeof(STUDENT) * n);

第一种方法,设置一个结构体变量的成员为某个具体的常量,进行遍历寻找得出变量的数量
第二种方法,在输入时计算
第三种,建立一个有指针域的动态链表

用第三种方法实现的一个例子,可用来学籍管理系统
#include
#include
#include

typedef struct student
{
int num;
char name[20];
char sex[3];
struct student *next;
}LIST;

LIST *CreateList()
{
int i,n;
LIST *head=NULL,*pre,*cur;
printf("请输入学生的总个数:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("正在输入第%d个学生数据!
",i);
pre=(LIST *)malloc(sizeof(LIST));
pre->next=NULL;
printf("请输入该学生的姓名:");
scanf("%s",&pre->name);
printf("请输入该学生的学号:");
scanf("%d",&pre->num);
printf("请输入该学生的性别:");
scanf("%s",&pre->sex);

if(NULL==head)
head=pre;
else
cur->next=pre;
cur=pre;
}
return head;
}

int GetNum(LIST *head)
{
int i=1;
while(head->next!=NULL)
{
i++;
head=head->next;
}
return i;
}

void Disp(LIST *head)
{
int i=1;
printf("正在输出学生信息!
");
while(head->next!=NULL)
{
printf("正在输入第%d个学生的数据!
",i++);
printf("学生姓名:%s
学生学号:%d
学生性别:%s
",head->name,head->num,head->sex);
head=head->next;
}
printf("正在输入第%d个学生的数据!
",i++);
printf("学生姓名:%s
学生学号:%d
学生性别:%s
",head->name,head->num,head->sex);
printf("学生信息输出结束!
");
}

void DestroyList(LIST *head)
{
LIST *pre=head;
while(head->next!=NULL)
{
pre=pre->next;
free(head);
head=pre;
}
}

int main(void)
{
LIST *head;
head=CreateList();
printf("一共有%d个学生数据!
",GetNum(head));
Disp(head);
DestroyList(head);
getch();
return 0;
}

满意采纳,不满意追问