我刚开始学习C语言,对于字符串指针和字符数组这些概念感到有些混淆。有没有人能帮我稍微澄清一下呢?
// source code
char name[10] = "Apple";
char *name2 = "Orange";
printf("the address of name: %p\n", name);
printf("the address of the first letter of name: %p\n", &(*name));
printf("first letter of name using pointer way: %c\n", *name);
printf("first letter of name using array way: %c\n", name[0]);
printf("---------------------------------------------\n");
printf("the address of name2: %p\n", name2);
printf("the address of the first letter of name2: %p\n", &(*name2));
printf("first letter of name2 using pointer way: %c\n", *name2);
printf("first letter of name2 using array way: %c\n", name2[0]);
// output
the address of name: 0x7fff1ee0ad50
the address of the first letter of name: 0x7fff1ee0ad50
first letter of name using pointer way: A
first letter of name using array way: A
---------------------------------------------
the address of name2: 0x4007b8
the address of the first letter of name2: 0x4007b8
first letter of name2 using pointer way: O
first letter of name2 using array way: O
我认为name和name2都指向它们自己的第一个字母的地址。那么我的困惑是(请参见下面的代码)
//code
char *name3; // initialize a char pointer
name3 = "Apple"; // point to the first letter of "Apple", no compile error
char name4[10]; // reserve 10 space in the memory
name4 = "Apple"; // compile errorrrr!!!!!!!!!!
我创建了一个名为name2的字符指针,并将name2指向"Apple"的第一个字母,这很好。然后我创建了另一个字符数组并在内存中分配了10个空间。接着我尝试使用name4,它是一个指向"Apple"第一个字母的地址。结果,编译错误。
我对这种编程语言感到非常沮丧。有时它们的工作方式相同,但有时它们却不同。有人能解释一下原因吗?如果我真的想在不同行上创建一个字符串或字符数组,我该怎么做呢?
非常感谢...