字符串赋值=和strcpy问题
#include<iostream>
#include<string.h>
using namespace std;
struct Student
字符串拷贝函数strcpy作用{
char name[10];
int num;
char sex;
};
int main()
{
Student *p;
p = new Student;
strcpy(p->name, "Wang Fun");
char chr[] = {"Wang Fun"};
// p -> name =  {"Wang Fun"}; 错误,数组之间不能直接赋值
p->num = 10123;
p->sex = 'M';
cout << p -> name << " " << p->num << " " << p -> sex <<endl;
delete p;
return 0;
}
关于字符串的赋值问题,⽹上说得很多,都谈论的是,⽤‘=’号时是指向同⼀地址,strcopy时是得到两个相同的字符串,但是却没有提及到修改问题。
其实,当⽤‘=’号赋值时,得到的字符串是不能够修改的,但是编译时却不会提⽰错误。⽽⽤strcpy复制时,可以对字符串修改,但在使⽤strcpy之前,应该⽤new或malloc等为字符串分配空间。
#include <iostream.h> #include <string.h>
int main()
{
char *str="hello";
str[0]='H';
cout<<endl<<str<<endl;
return 0;
}
执⾏结果:
....关闭
#include <iostream.h> #include <string.h>
int main()
{
char *str;
str=new char;
strcpy(str,"hello");
str[0]='H';
cout<<endl<<str<<endl;
return 0;
}
执⾏结果:
Hello