简体   繁体   English

如何在结构中使用malloc或new?

[英]how to use malloc or new in struct?

How to use malloc to allocate memory instead for char name[50]; 如何使用malloc代替为char name[50];分配内存char name[50]; I don't know these concepts am new for c . 我不知道这些概念对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;
}

With the following statement you have only allocated memory that can occupy only one student . 使用以下语句,您仅分配了只能占用一个student内存。

s = (struct student *) malloc (sizeof(struct student));

But what you need is an array of students sized c , so you have to allocated c times the memory you have allocated now, so you can use them as s[i] : 但是,您需要的是大小为c的学生数组,因此您必须分配c乘以现在分配的内存,以便可以将它们用作s[i]

s = (struct student *) malloc (c * sizeof(struct student));
char name[50];

Declares and allocate an array of 50 chars. 声明并分配50个字符的数组。 If you want to allocate an array dynamically, you can use malloc : 如果要动态分配数组,可以使用malloc

char *name = malloc(n*sizeof(char));

Where n is the desired number of elements (50 in our example). 其中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);

However, there is no reason to do so, as long as NAME_LENGTH is known at compile-time. 但是,只要在编译时就知道NAME_LENGTH,就没有理由这样做。

Don't forget to free each allocated memory block once they no longer needed. 不要忘记在不再需要每个已分配的内存块时free它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM