c - 设置后如何更改 char * const 的内容 (C)

标签 c pointers

我们正在处理一个常量指针, 所以它持有的地址不能改变。 但是该引用的内存地址的内容应该是可变的...

我仍然在尝试这样做时遇到编译/段错误。

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char * const c_ptr = "firstValue"; // now c_ptr is a const ptr to an immutable string literal, 
                                     //we can't change it unless we declare char [] instead 
    printf("%s",c_ptr);

    *c_ptr="hsdsdsd"; // better to use strcpy(c_ptr, "hsdsdsd");   

    printf("%s",c_ptr);
    return 0;
}

main.c: In function 'main':
main.c:8:8: warning: assignment makes integer from pointer without a cast [enabled by default]
*c_ptr="hsdsdsd";

Segmentation fault (core dumped)

最佳答案

好吧,对于常量指针,指针指向的数据可以更改,但当您使用字符串文字对其进行初始化时则不会。它们具有 char * 类型但无法更改的相当奇怪的特性。

所以,你可以这样做:

char data[10] = "foobar";
char * const ptr = data;

printf("%s\n", ptr);  // prints foobar
*ptr = 'z';
printf("%s\n", ptr);  // prints zoobar

关于c - 设置后如何更改 char * const 的内容 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226374/

相关文章:

c - PortAudio 对连续输入流的实时音频处理

c - 在二维数组中搜索元素,C 编程

c - 如何删除指针数组的第一个值?

c - 如何使用 strtok 剪切大小不同的字符串?

c - 即使使用 volatile ,变量也不会更新,没有线程

c - 当我尝试在函数中添加节点但在主函数中工作时,为什么我的程序崩溃了

C++ 将字符从 int append 到 std::string

c - 某些 C 函数如何接受空参数?

使用 std 安全指针相互链接的 c++ 类 (c++)

c - 如何在 C 中接收 connect-n 的输入