给结构体中字符数组的赋值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/melody_1016/article/details/83345399

先看一段代码:
 

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
	char name[10];
	char sex;
	int age;
};

int main()
{
	struct Stu stu;
	stu.name = "hello";//直接赋值
	printf("%s\n", stu.name);
	
	system("pause");
	return 0;
}

结果:

原因:

(1)首先,其实是忘记了C++的基础问题,C++里面只要涉及char都不能直接通过“=”来赋值,因为C++里面没有提供这个功能。必须使用str开头的函数。只有后来的CString重载来“-,+,=”之后才可以怎么方便的使用。CString str;str=“sasa";.
(2)其次,stu.name="hello";//报错为什么?name[10]是一个10大小的内存空间,而”hello“是一个常量匿名字符串的地址,现在你应该明白了.
你把一个地址赋值给了数组,也就是说现在char[20]="0x51825182"之类的,get it !

总结:结构体字符数组的赋值必须用字符串函数,不能直接进行赋值。

猜你喜欢

转载自blog.csdn.net/melody_1016/article/details/83345399
今日推荐