gpt4 book ai didi

c - 为什么 C 中指针与整数和字符串的行为不同

转载 作者:行者123 更新时间:2023-11-30 17:08:18 25 4
gpt4 key购买 nike

我现在正在学习 C,并试图理解为什么下面的第一个代码片段可以工作,但第二个代码片段却不能。

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

int main(void)
{
char *s = malloc(strlen("Hello!") + 1);
s = "Hello!\0"; //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!\0"; //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!\0" 是。在这两种情况下,您只需丢弃 malloc 的返回值,因为您将指针设置为指向其他内容。

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

关于c - 为什么 C 中指针与整数和字符串的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com