指向字符数组输出的指针

问题描述

当我们声明一个指向任何整数的指针时,我们像这样声明它

int i=5;
int *p=&i;

我们使用*p获取值5,如果我们想要地址,我们使用不带星号的p获取地址。但是在字符数组的情况下,当我们说

char *str="HELLO";

我们仅使用str获取"HELLO"作为printf函数输出。像这样

printf("%s",str);

这里我们使用str,但不带星号。

为什么当我们使用不带星号的指针变量时,如果获取指向整数的指针的地址,我们为什么不获取地址,而是获取“ HELLO”作为输出

解决方法

首先int *p=5;是错误的!您不能在指针的声明中做到这一点。到那时,指针就可以得到地址了。您应该先执行int *p;,然后执行*p = 5;来为其分配值。

printf("%s",str); // prints the value of the variable,because its a pointer.
printf("%s",*str); // the * will cause to a segmentation fault

int *p // the * there is just used to tell the compiler that you are declaring a pointer of type integer.

/* another scope after declaring your pointer */

*p //is used to get value of a pointer variable.(dereference it)
&p //is used to get the adress of a pointer variable.
p //contains an adress.