如何在结构中使用malloc或new?
如何使用malloc为如何在结构中使用malloc或new?,c,pointers,struct,malloc,C,Pointers,Struct,Malloc,如何使用malloc为charname[50]分配内存我不知道这些概念对于c来说是新概念 struct student { char name[50]; int roll; float marks; }; int main() { int c; printf("no. of students\n"); scanf("%d",&c); struct student *s; s=(struct student *) ma
charname[50]分配内存
我不知道这些概念对于c
来说是新概念
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
int c;
printf("no. of students\n");
scanf("%d",&c);
struct student *s;
s=(struct student *) malloc (sizeof(struct student));
int i;
printf("\nstudents information:\n");
for(i=0;i<c;++i)
{
printf("enter the name:");
scanf("%s",s[i].name);
printf("enter roll no:");
scanf("%d",&s[i].roll);
printf("enter the marks:");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("\ndetails of all the student:\n");
for(i=0;i<c;++i)
{
printf("the student name:%s\n",s[i].name);
printf("the student roll no. is:%d\n",s[i].roll);
printf("the student mark is:%.2f\n",s[i].marks);
printf("\n");
}
return 0;
}
struct学生
{
字符名[50];
整流罩;
浮标;
};
int main()
{
INTC;
printf(“学生人数”);
scanf(“%d”、&c);
结构学生;
s=(结构学生*)malloc(大小(结构学生));
int i;
printf(“\n学生信息:\n”);
对于(i=0;i
声明并分配一个50个字符的数组。
如果要动态分配数组,可以使用malloc
:
char *name = malloc(n*sizeof(char));
其中n
是所需的元素数(在我们的示例中为50)。使用以下语句,您只分配了只能占用一个学生的内存
s = (struct student *) malloc (sizeof(struct student));
但是您需要的是一个学生数组,大小为c
,因此您必须分配c
倍于您现在分配的内存,以便您可以将它们用作s[i]
:
s = (struct student *) malloc (c * sizeof(struct student));
struct学生
{
字符*名称;
整流罩;
浮标;
};
#定义名称\u长度128
int i;
struct student*s=malloc(sizeof(struct student)*c);
对于(i=0;i
但是,只要在编译时知道NAME_LENGTH,就没有理由这样做
<>不要忘记< C++ >代码>每个分配的内存块一旦不再需要。< /P>这是C还是C++?它看起来像普通C,但是你也提到了<代码>新< /代码>。请适当地标记。Stackoverflow不是真正的在任何主题中获得介绍信息的地方。如果你是C的新手,需要熟悉WI。基本知识,然后是一本教程或书。变量不是预先声明的-我不熟悉较新的标准,但它显然不是ANSI C…另请参阅感谢opd的快速回复,但如果我尝试动态显示其错误,请编辑我的程序并粘贴在此处。。thankyou@user3351563听起来你好像在编译我作为C++,OPD编写了一个纯C解决方案,即没有铸造Maloc的返回值,这也是正确的方法。当你使用C++编译器时,它会抱怨返回值,而你不得不使用一个类型的CaskHyu ARJUR右键。但是如何动态地分配而不是字符名称[50 ]。请help@user3351563你不能直接在struct
定义中分配内存。在struct
定义中有指针,当你使用它时,动态分配内存,如上所述。所以你的struct学生应该有char*name
。只需复制和编辑我的程序我不知道如何使用它替换字符名[50];@user3351563将char*name
替换为char*name
。以后您可以执行s[1]。name=(char*)malloc(SOME_SIZE*sizeof(char))
操作,然后再将某些值放入或扫描到其中。
s = (struct student *) malloc (c * sizeof(struct student));
struct student
{
char *name;
int roll;
float marks;
};
#define NAME_LENGTH 128
int i;
struct student *s = malloc(sizeof(struct student) * c);
for(i = 0; i < c; i++)
s[i].name = malloc(NAME_LENGTH);