为什么可以在C中将字符串分配给字符指针,而不能将整数值分配给整数指针 [英] Why it is possible to assign string to character pointer in C but not an integer value to an integer pointer

查看:83
本文介绍了为什么可以在C中将字符串分配给字符指针,而不能将整数值分配给整数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在下面的代码int * p = 22中会给出编译时错误,而ptr将成功打印该值.

why in the below code int *p = 22 will give compile time error and ptr will print the value successfully .

int main()
{

/*taking a character pointer and assigning a string to it*/
char *ptr = "Stackoverflow" ; //correct

/*taking a int pointer and assigning a string to it*/
int *p = 22 ; //incorrect

printf("%s",ptr); // correct and print
printf("%d",p); //incorrect and give compile time error.

return 0;
}

推荐答案

例如,如果您有字符数组

If you have a character array as for example

char s[] = "Stackoverflow";

然后将表达式中使用的数组指示符转换为指向其第一个元素的指针.所以你可以写

then the array designator used in expressions it is converted to pointer to its first element. So you may write

char *ptr = s;

指针ptr现在指向数组s的第一个字符.

The pointer ptr now points to the first character of the array s.

C语言中的字符串文字也像字符数组一样表示,并像字符数组一样以静态存储持续时间存储在内存中.

String literals in C are also represented like character arrays and stored in memory like character arrays with the static storage duration.

例如,字符串文字"Stackoverflow"具有类型char[14](包括结尾的零).

So for example the string literal "Stackoverflow" has the type char[14] (including the terminating zero).

所以你写

char *ptr = "Stackoverflow";

那么如果有的话,这句话实际上是相同的

then this statement in fact the same if there would be

static char unnamed[] = "Stackoverflow";
char *ptr = unnamed;

至此声明

int *p = 22 ;

然后,整数文字不转换为指向其本身的指针.它实际上代表数字22,仅此而已.

then the integer literal is not converted to a pointer to itself. It represents literally the number 22 and nothing more.

所以编译器会发出一条消息,因为如果您希望指针确实包含整数值22,则必须使用强制转换.

So the compiler issues a message because if you want that the pointer indeed contained the integer value 22 then you have to use a casting.

表达式

22 == 22

总是产生true.

这个表达式

"Stackoverflow" == "Stackoverflow"

不必产生true,因为根据编译器选项,编译器可以将重合字符串文字放在不同的存储区中.在此表达式中,将比较指向字符串文字的第一个字符的指针.

is not necessary yields true because depending on compiler options the compiler can place coincidental string literals in different memory areas. And in this expression it is the pointers to the first characters of the string literals that are compared.

请注意,如果要输出指针指向的整数对象,则需要使用解引用.所以无论如何都不要

Take into account that if you are going to output an integer object pointed to by a pointer you need to use dereferencing. So in any case instead of

printf("%d",p); 

您应该写

printf("%d", *p); 

或者,如果要输出存储在指针中的值,则必须使用其他格式说明符

Or if you want to output the value stored in a pointer you have to use another format specifier

printf("%p", p); 

这篇关于为什么可以在C中将字符串分配给字符指针,而不能将整数值分配给整数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆