C言語:深いコピーVS浅いコピー配列VSポインタ
コンピュータは32ビットで、コンパイラはdev-cppです.
Cソース:
実行結果:
Cソース:
#include <stdio.h>
struct student{
char *name1;
char name2[20];
}stu;
int main()
{
struct student *p;
p = &stu;
//strcpy((*p).name1,"first");// , , 。
strcpy((*p).name2,"second"); // :
printf("name1 = %s \t name2 = %s
",(*p).name1,(*p).name2);
p->name1 = "third"; // ,
printf("name1 = %s \t name2 = %s
",(*p).name1,(*p).name2);
//p->name2 = "fourth"; // : incompatible types in assignment of `const char[7]' to `char[20]'
char tp[20]="fifth";
//p->name2 = tp; // :ISO C++ forbids assignment of arrays
//
strcpy((*p).name2,tp);
p->name1 = tp;
tp[0]='F';// tp
printf("name1 = %s \t name2 = %s
",(*p).name1,(*p).name2); // ,
//
printf("sizeof(char *name) = %d
sizeof(char name[20]) = %d
", sizeof(p->name1), sizeof(p->name2)); // 32 4 20
system("PAUSE");
return 0;
}
実行結果:
name1 = (null) name2 = second
name1 = third name2 = second
name1 = Fifth name2 = fifth
sizeof(char *name) = 4
sizeof(char name[20]) = 20