strcpy对结构体的指针类成员操作

C语言 码拜 7年前 (2017-04-20) 1450次浏览
# include <stdio.h>
# include <string.h>
struct Student
{
char name[130];
int score;
Student *next;
};
int main()
{
Student *st_3;
strcpy(st_3->name,”jay”);
printf(“第三个学生的名字是%s\n:”,st_3->name);
return 0;
解决方案

10

引用:

运行有问题 语法没问题

Student *st_3;  //野指针,定义了一个指针但没有指向有效的对象
假如定义一个结构体对象Student st_3; 就没有问题

30

指针必须要分配空间后才能使用,否则指向的是未知区域(野指针),你尝试向未知区域进行写操作会出现异常

# include <stdio.h>
# include <string.h>
#include <stdlib.h>
struct Student
{
	char name[130];
	int score;
	Student *next;
};
int main()
{
	Student *st_3 = (Student *)malloc(sizeof(Student));
	strcpy(st_3->name, "jay");
	printf("第三个学生的名字是:%s\n", st_3->name);
	return 0;
}

10

你的Student *st_3; 没有分配内存
你可以直接创建一个对象:
Student st_3;
而不是一个指针

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明strcpy对结构体的指针类成员操作
喜欢 (0)
[1034331897@qq.com]
分享 (0)