怎样动态建立一个结构体数组并给它赋值?

tdxue 2003-06-13 11:02:47
有一个结构:
struct student
{
int id;
char name;
};


我想在程序运行的时候动态构造一个该结构的结构体数组并赋值:

cin>>m;
struct student stuarray[m];
for(int i=0;i<m;i++)
cin>>stuarray[i].id>>stuarray[i].name;

但是这样肯定不行,我也想不出其他的办法了。动态数组我会建,可是数组的元素类型都必须是一样的,所以有没有动态建立结构数组的方法阿?(其他办法也行 ) 呵呵 见笑
谢谢回复!
...全文
551 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
topikachu 2003-06-13
  • 打赏
  • 举报
回复
在c中用malloc和free
Daybreakspider 2003-06-13
  • 打赏
  • 举报
回复
但是如果不用C++, 在C中怎么实现呢?
rtdb 2003-06-13
  • 打赏
  • 举报
回复
哇, 不会吧, 基本上一样啊,好象抄的。

那个...所见略同:-)
arfi 2003-06-13
  • 打赏
  • 举报
回复
#include <iostream.h>

struct student
{
int id;
char name;
};

void main(void)
{
int m;
student *p;

cin>>m;
p = new student[m];
for(int i=0; i<m; i++)
{
p[i].id = 1;
p[i].name = 'N';
}
}
rtdb 2003-06-13
  • 打赏
  • 举报
回复
cin>>m;
student* stuarray = new student[m];
for(int i=0;i<m;i++)
cin>>stuarray[i].id>>stuarray[i].name;

大约这样就可以了, 最后不用stuarray时记得用delete把它删除。
晨星 2003-06-13
  • 打赏
  • 举报
回复
用完了别忘delete。
晨星 2003-06-13
  • 打赏
  • 举报
回复
cin>>m;
student* stuarray = new student[m];
for(int i=0;i<m;i++)
cin>>stuarray[i].id>>stuarray[i].name;
boyfling 2003-06-13
  • 打赏
  • 举报
回复
new啊,很简单
magic007 2003-06-13
  • 打赏
  • 举报
回复
以上程序printf("p[i] id=%d,p[i] name=%s\n",p[i].id,p[i].name);
改为printf("p[%d] id=%d,p[%d] name=%s\n",i,p[i].id,i,p[i].name);
magic007 2003-06-13
  • 打赏
  • 举报
回复
一个在C中的例子。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int id;
char name[20];
};
void main()
{
struct student *p;
char tmp[10];
int m;
int i;
printf("input m:");
scanf("%d",&m);
p=malloc(m*sizeof(struct student));
for (i=0;i<m;i++){
p[i].id=i;
itoa(i,tmp,10);
strcpy(p[i].name,"name ");
strncat(p[i].name,tmp,strlen(tmp));
}
for (i=0;i<m;i++)
printf("p[i] id=%d,p[i] name=%s\n",p[i].id,p[i].name);
free(p);

}

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧