您的位置:首页 > 编程语言 > C语言/C++

C语言 结构体中使用strcpy方法,以及结构体指针

2017-03-22 16:49 323 查看
今天项目中需要使用结构体,为char *型赋值肯定要使用strcpy。

但是关键是是试了几次都是错的,因此百度了一下。发现网上很多很多都是错误的,都会报段错误。

因此请教大神才解决。

关键就是,在使用strcpy之前,一定要对char* 型属性进行申请内存!

下面直接看例子:

#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct stu{
int age;
char* name;
};

void pr(struct stu *pstu)
{
printf("%s",pstu->name);
}

int main()
{
struct stu student;
struct stu *pstudent=&student;
student.age=20;
student.name=(char *)malloc(10);
strcpy(student.name,"xiaoming");
pr(pstudent);
return 0;
}

以上代码无警告无报错更没有段错误,完美执行!

完!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐