[英]how to use malloc or new in struct?
如何使用malloc代替為char name[50];
分配內存char name[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;
}
使用以下語句,您僅分配了只能占用一個student
內存。
s = (struct student *) malloc (sizeof(struct student));
但是,您需要的是大小為c
的學生數組,因此您必須分配c
乘以現在分配的內存,以便可以將它們用作s[i]
:
s = (struct student *) malloc (c * sizeof(struct student));
char name[50];
聲明並分配50個字符的數組。 如果要動態分配數組,可以使用malloc
:
char *name = malloc(n*sizeof(char));
其中n
是所需的元素數(在我們的示例中為50)。
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);
但是,只要在編譯時就知道NAME_LENGTH,就沒有理由這樣做。
不要忘記在不再需要每個已分配的內存塊時free
它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.