好问题,先比较一下:
char* str1 = "hello";
const char* const str1 = "hello";
char str1[] = "hello";
在char* str1 = "hello";str1 中是一个指向char 类型的指针。您可以进行指针运算,str1++ 将编译,这会将数据放入内存的只读部分(常量数据)。并使用 str1[0]='a';将导致运行时错误(但编译正常)。
const char* const str1 = "hello"; 中的数据和指针是 const:使用 str1[0]='a'; 会导致编译错误。
在char str1[] = "hello"; str1 中是一个数组(常量指针)。使用str1[0]='a'; 是可以的,但是使用str1++ 会导致编译错误:
#include <stdio.h>
void reverse(char *p){
char c;
char* q = p;
while (*q) q++;
q--; // point to the end
while (p < q) {
c = *p;
*p++ = *q;
*q-- = c;
}
}
int main(){
char s[] = "DCBA";
reverse( s);
printf("%s\n", s); // ABCD
}
第二个:
指针的好处是:指针也是一个变量,就像 'int' 有一个区别:
使用带有 int 的 i++ 只会在 i 上加一,但带有指针的 p++ 会增加一个底层类型的内存大小,例如int32_t* p; p++ 将 4(int32_t 大小)添加到 p 值。
p++ 增加 p 变量内存本身,而不是它可能指向的内存。(这是您正在寻找的答案)。
现在比较一下:
int ary[] = { 1, 2, 3 };
//int* p2 = { 1, 2, 3 };
int* p = ary;
const int* const q = ary;
在此示例中:
#include <stdio.h>
int main() {
int ary[] = { 1, 2, 3 };
//int* p2 = { 1, 2, 3 };
int* p = ary;
const int* const q = ary;
ary[0] = 10; // ok
p[0] = 100; // ok
//q[0] = 11; // error
printf("%x\n", p);
printf("%d\n", p[0]); // 100
return 0;
}
虽然char* str1 = "hello"; 有效,但int* p2 = { 1, 2, 3 }; 无效。 char* p2 = { 'h', 'e', 'l', 'l', 'o', 0 }; 也无效。所以char* str1 = "hello"; 是编译时的特殊编译器技巧,它将“hello”放入只读内存空间。
我希望这会有所帮助。