在 C 语言中,可以像这样在声明中使用字符串字面量:
char s[] = "hello";
或者像这样:
char *s = "hello";
那么它们有什么区别呢?我想知道在编译时和运行时的存储持续时间实际上发生了什么。
在 C 语言中,可以像这样在声明中使用字符串字面量:
char s[] = "hello";
或者像这样:
char *s = "hello";
那么它们有什么区别呢?我想知道在编译时和运行时的存储持续时间实际上发生了什么。
char *str = "Hello";
以上代码将str指向程序二进制映像中硬编码的文本值"Hello",该值在内存中被标记为只读,这意味着任何对该字符串常量的更改都是非法的,并会导致分段错误。
char str[] = "Hello";
将字符串复制到堆栈上新分配的内存中。因此,对其进行任何更改都是允许和合法的。
means str[0] = 'M';
将字符串更改为"Mello"。
有关更多详细信息,请查看类似问题:
char *s1 = "Hello world"; // Points to fixed character string which is not allowed to modify
char s2[] = "Hello world"; // As good as fixed array of characters in string so allowed to modify
// s1[0] = 'J'; // Illegal
s2[0] = 'J'; // Legal
const DBJ* p means "p points to a DBJ that is const"
也就是说,通过 p 无法更改 DBJ 对象。
DBJ* const p means "p is a const pointer to a DBJ"
也就是说,你可以通过 p 改变 DBJ 对象,但是你不能改变指针 p 本身。
const DBJ* const p means "p is a const pointer to a const DBJ"
也就是说,您不能更改指针p本身,也不能通过p更改DBJ对象。
试图更改常量的错误在编译时被捕获。const没有运行时空间或速度惩罚。
(当然,假设您正在使用C++编译器?)
--DBJ