C / C++ Char字符各种练习,包括字符数组、字符指针和结构体操作方法和优缺点
引言
今天在看结构体变量时发现一个问题,问题代码如下【网络上的】:
int main() {
struct student{
char c[20];
}s1;
s1.c="china";
printf("%s",s1.c);
return 0;
}
输出结果为空,不知道是为什么?
经过网上的答案尽是如此:
(1)首先,其实是忘记了C++的基础问题,C++里面只要涉及char都不能直接通过“=”来赋值,因为C++里面没有提供这个功能。必须使用str开头的函数。只有后来的CString重载来“-,+,=”之后才可以怎么方便的使用。CString str;str=“china";.
(2)其次,s1.name="china"; //报错为什么?name[10]是一个10大小的内存空间,而”hello“是一个常量匿名字符串的地址,现在你应该明白了.
一、Char字符数组
1、定义的时候直接用字符串赋值
char a[10]="hello"; //sizeof(a)为10
或char a[]="hello"; //不指定数组大小,sizeof(a)为6
注意:不能先定义再给它赋值,如char a[10]; a[10]="hello";这样是错误的!
2、对数组中字符逐个赋值
char a[10]={'h','e','l','l','o'}; //sizeof(a)为10
或char a[]={'h','e','l','l','o'}; //不指定数组大小,sizeof(a)为5
3、利用strcpy, memcpy, 先定义再赋值。
char a[10];
strcpy(a, "hello");
想要直接给数组赋值字符串除了在初始化时赋值,还可以通过两个函数:
void *memcpy(void*dest, const void *src, size_t n);
void strcpy(str1,str2);
4、常见字符串函数
注意要使用strcpy函数要用#include <string.h>包含string.h头文件。
typedef struct Student
{
int grade;
char name[128];
} Student;
// 字符串赋值
char dst[10]; /* not enough for all of src */
strcpy(dst, src); // Bug,如果这个是危险的,可能会越界!
strncpy(dst, src, sizeof(dst) - 1); // OK ... but `dst` needs to be NUL terminated
// 结构体内字符串赋值
struct Student stu1 = {1, “Name”};
stu1.grade = 1;
strcpy(stu1.name, “James Wei”);
memcpy(stu1.name, “James Wei”, strlen(“James Wei”));
struct Student stu2 = {1, “Name”};
stu2.grade = 2;
strcpy(stu2.name, “Tony Scott”);
memcpy(stu2.name, “Tony Scott”, strlen(“Tony Scott”));
// 字符串比较
if (strcmp(stu1.name, stu2.name) != 0) {
// 字符串内容不相同
}
// 字符串长度计算
int length = strlen(stu1.name);
优缺点:
1. 不用关心内存释放问题,
2. 内容存放的地方安全;
3. 函数方法内,如果要改变结构体内的成员值,创建函数的参数可以是结构体地址,用指针来传递。
4. 注意字符串申请的长度。
5. 为了struct直接复制方便,char最好是设置为char[n],而不是char*。
6. 自己领会,应用到你的项目里面,真机练习:
{
typedef struct Student
{
int grade;
char name[128]; // 注意是字符数组,不是char*字符串指针
} Student;
Student stu1 = {1, "Name"};
stu1.grade = 1;
strcpy(stu1.name, "James Wei");
fprintf(stderr, "stu1.name:%s\n", stu1.name);
Student stu2 = {1, "Name"};
stu2.grade = 2;
strcpy(stu2.name, "Tony Scott");
fprintf(stderr, "stu2.name:%s\n", stu2.name);
// 多样测试
Student stu3;
stu3 = stu2; // 可以直接赋值
fprintf(stderr, "stu3.name:%s\n", stu3.name);
strcpy(stu3.name, "Ally Rong"); // 修改stu3.name,不会造成stu2.name的改变
fprintf(stderr, "stu2.name:%s\n", stu2.name); //
fprintf(stderr, "stu3.name:%s\n", stu3.name);
// stu3.name = stu1.name; // 编译报错,结构体内的字符数组不可以这样直接赋值,也是需要用strcpyr方法
}
二、Char字符指针
待续...