C中用scanf赋值给某个结构体成员(字符数组),怎么始终为null?请大家指教

来源:百度知道 编辑:UC知道 时间:2024/06/17 05:23:53
#include <stdio.h>
main()
{
struct student
{ char name[10];
int age;
};
struct student *p=NULL;
scanf("%s%d",&p->name,&p->age);
printf("%s,%d",p->name,p->age);
}
屏幕输入:yang 21
屏幕输出:(null),21Null pointer assignment。为什么始终为null?
而下面这种不用结构体,不用指针的就正常:
#include <stdio.h>
main()
{
int i;
char a[10];
scanf("%s%d",&a,&i);
printf("%s,%d\n",a,i);
}

struct student *p=NULL;//此时指针赋值为空(NULL),此时p为空指针,
正确的做法是给p分配个指针:
#include <stdio.h>
main()
{
struct student
{ char name[10];
int age;
};
struct student *p=NULL;
p = new student;//分配一个
scanf("%s%d",&p->name,&p->age);
printf("%s,%d",p->name,p->age);
delete p;
}

struct student *p=NULL; 你只给结构分配了一个指针,实际上并没有分配数据存储单元。

char a[10]; a是数组,分配了数据存储单元
int i; 分配了数据存储单元
------------------------------------------------
你需要给 p 分配数据存储单元, 用 new, 用 malloc 或 直接声明为 struct student p;都可以

正确格式应该是这样
#include <stdio.h>
main()
{
struct student
{ char name[10];
int age;
};
struct student *p=NULL;
scanf("%s%d",p->name,&p->age);
printf("%s,%d",p->name,p->age);
}
你试一试

#include <stdio.h>
main