繁体   English   中英

我试图在结构中使用malloc分配内存,但是没有用?为什么?

[英]I tried to allocate memory using malloc in a structure but it didn't work?Why?

## Code to read general information ##
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>    
typedef struct{
    char *name =(char*)malloc(20);
    int age;
    int id;
}info;
main()
{
    info a;
    printf("Enter Name :");
    scanf(" %[^\n]",a.name);
    a.age=19;
    a.id=11700055;
    printf("Name :%s\nAge :%d\nId :%d\nSize of info 
:%d\n",a.name,a.age,a.id,sizeof(a));
    return 0;
}




  https://i.stack.imgur.com/WoA0T.png

此代码有什么问题? 它显示错误,我不了解,例如info没有名为“ name”的成员?

它还说姓名,年龄,身份证不是信息的成员。

在struct声明中,您正在分配不允许的内存。

如果您需要其中的数组

typedef struct{
    char name[20];
    int age;
    int id;
}info;

或者,您可以执行此操作

#define MAXLEN 20

    typedef struct{
        char* name;
        int age;
        int id;
    }info;

info p;
p.name = malloc(MAXLEN);
if(!p.name){ perror("malloc");exit(1);}
...

它应该是int main(void)而不是main()

暂无
暂无

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

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