数组赋给数组
2018-04-19 本文已影响0人
calm_peng
遇到的问题:c++中一个数组传给另一个数组时不比配的问题
正确版本1:
#include "iostream"
#include"string"
using namespace std;
class Student{
private:
char *sno,*sname;
int age;
public:
Student(char sno[],char sname[],int age){
this->sno = sno;
this->sname = sname;
this->age = age;
}
void print(){
cout<<"sno:"<<sno<<" sname:"<<sname<<" age:"<<age<<endl;
}
};
int main(){
char sno[10],sname[20];
int age;
while(cin>>sno>>sname>>age){
Student A(sno,sname,age);
A.print();
return 0;
}
}
结果
正确2:
//....
public:
Student(char* sno,char * sname,int age){
this->sno = sno;
this->sname = sname;
this->age = age;
}
//....
数组名和指针皆为地址,不影响。但是有区别这两者,前者指的是数组的第一个元素的地址,并且是不可改的,常量指针,改了的话,那块地址的数组就无法使用,会内存溢出
;后者是可改的。
下面这个更具体:
https://segmentfault.com/q/1010000003793687
错误1:
//...
public:
Student(char[] sno,char[] sname,int age){
this->sno = sno;
this->sname = sname;
this->age = age;
//...
错误
char[] a; java风格
char a[]; c/c++风格
错误2:
class Student{
private:
char sno[10],sname[20];
int age;
public:
Student(const char* sno,char * sname,int age){
this->sno = sno;
this->sname = sname;
this->age = age;
}
理由正如上面所说,数组名(地址)不可改(赋值)。
只能用 strcpy ,memcpy.
To copy the content into the array, you need to use
strcpy()
fromstring.h
(char
array) ormemcpy()
in general.
正确:
class Student{
private:
char sno[10],sname[20];
int age;
public:
Student( char* sno,char * sname,int age){
strcpy(this->sno,sno);
strcpy(this->sname,sname);
// this->sno = sno;
// this->sname = sname;
this->age = age;
}
总结:
概念不清,没有细细的理解。数组和指针的熟练度太低。