我现在正在学习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 = 5
与s = "Hello!"
,我猜测字符串文字与int的传递方式有所不同(但我不完全确定它是什么)。
对于printf
的两种不同用途,我有点困惑。如果我将s
传递给printf
,是否应该打印出s
的地址而不是实际的字符串?
答案 0 :(得分:0)
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
是指向整数的指针。