C-如何在struct中使用malloc或新的



如何使用malloc为char name[50];分配内存,我不知道这些概念是c的新概念。

struct student
{
    char name[50];
    int roll;
    float marks;
};
int main()
{
    int c;
    printf("no. of studentsn");
    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:%sn",s[i].name);
        printf("the student roll no. is:%dn",s[i].roll);
        printf("the student mark is:%.2fn",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不再需要的每个分配的内存块。

最新更新