struct 中的 char* 是可重写的,但 main() 函数中的 char* 则不可重写。为什么?

标签 c string pointers literals

我想知道相同的 char* 驻留在结构体ma​​in()函数中的区别。

这是代码:

struct student {
    char* name;
};

int main() {

    // char* in struct
    struct student bob;
    bob.name = "alice";
    bob.name = "bob";
    printf("name: %s\n", bob.name);

    // char* in main()
    char *name = "kim";
    *name = "lee";
    printf("name: %s\n", name);

    return 0;
}

输出:

name: bob
name: kim

在使用struct的情况下,学生bob.name的值从“alice”更改为“bob”。但是,在后一种情况下,char* name 的值并未更改。

我认为“kim”没有更改为“lee”的原因是 char *name 指向字面值“kim”。

如果我是对的,为什么 bob.name 从“alice”更改为“bob”?它不应该更改为“bob”,因为“alice”也是字面意思。

有什么区别?

最佳答案

您的代码调用未定义的行为

既然你这样做了:

struct student { char* name;};
struct student bob;
bob.name = "alice";

即您正在使指针 name 指向字符串文字。

然后你只需:

bob.name = "bob";

使指针指向另一个字符串文字,这是可以的,因为您只需修改指针指向的位置,而不是它指向的字符串文字(例如 bob.name[3] = 'f' ;,这会导致段错误,因为它会尝试修改字符串文字 - 禁止)。

如果您打算让指针指向字符串文字,那么我建议您这样声明:

const char* name;

它允许您更改指针指向的位置,但不能更改指针指向的字符串文字的内容。

<小时/>

现在这个:

char *name = "kim";

是一个字符串文字,其内容无法修改。当你这样做时:

*name = "lee";

你只是做了一些不允许的事情,导致程序格式错误。

关于struct 中的 char* 是可重写的,但 main() 函数中的 char* 则不可重写。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46766787/

相关文章:

c++ - 从 C++ 函数返回字符串数组

c++ - 将C的char数组转换成C++的字符串

C 在调整哈希表大小时遇到​​问题

c - 有没有办法在多线程应用程序中安全地使用 errno?

c - 为共享内存初始化结构体中的 int

php - 在 pg_prepare 中使用 LIKE 通配符

c++ - typedef 类型和相同类型的指针的正确方法是什么?

c - 在头文件中声明时无法识别结构

c++ - 我可以将普通文件链接到我的可执行文件吗?

c# - 将 c++ dLL 的 char 指针数组传递给 c# 字符串