为什么指针在 C 中与 int 和 string 的行为不同

Why do pointers behave differently with ints vs strings in C

我现在正在学习 C,并且正在尝试理解为什么下面的第一段代码有效,而第二段却不行。

我在这里创建一个 char* 并为其分配一个字符串(这很好用):

int main(void)
{
    char *s = malloc(strlen("Hello!") + 1);
    s = "Hello![=10=]"; //Why am I able to do this without dereferencing (i.e., *s)?
    printf("%s\n", s); //Why don't I need to dereference s here?
}

这里我创建了一个 int* 并为其赋值(这个不行):

int main(void)
{
    int *i = malloc(sizeof(int));
    i = 5; //I get that this doesn't work because I'm not dereferencing i. Why does the above code with 's' not have the same issue?
    printf("%i\n", i); //I also understand what the issue is here. What confuses me is why the printf above doesn't have the same issue.
}

对于 i = 5s = "Hello!",我猜测字符串文字与整数的传递方式存在一些差异(但我不完全确定它是什么)。

对于printf的两种不同用法,我比较困惑。如果我将 s 传递给 printf,它不应该只打印出 s 的地址而不是实际的字符串吗?

int main(void)
{
    char *s = malloc(strlen("Hello!") + 1);
    s = "Hello![=10=]"; //Why am I able to do this without dereferencing (i.e.,*s)?
    printf("%s\n", s); //Why don't I need to dereference s here?
}

这将适用于整数:

int main(void)
{
    int *i = malloc(sizeof(int));
    i = (int *) 5; //I get that this doesn't work because I'm not dereferencing i. Why does the above code with 's' not have the same issue?
    printf("%i\n", (int) i); //I also understand what the issue is here. What confuses me is why the printf above doesn't have the same issue.
}

您只需要强制转换,因为 5 不是指针,而 "Hello![=13=]" 是。在这两种情况下,您只需丢弃 malloc 的 return 值,因为您将指针设置为指向其他内容。

所以简短的回答是他们的行为没有什么不同。您只是在一种情况下使用匹配类型(s 是指向 char 的指针,"Hello![=13=]" 可转换为指向 char 的指针),而在第二种情况下使用不匹配的类型(5 是一个整数而 i 是一个指向整数的指针。