简体   繁体   English

指向字符数组输出的指针

[英]Pointer to character array output

When we declare a pointer to any integer say we declare it like当我们声明一个指向任何整数的指针时,说我们声明它像

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

We use *p to get the value 5 and if we want the address we use p without asterisk sign to get the address.我们使用*p来获取值 5,如果我们想要地址,我们使用不带星号的p来获取地址。 But in case of character array, when we say但是在字符数组的情况下,当我们说

char *str="HELLO";

We simply use str to get "HELLO" as output in printf function.我们只是使用str来获取"HELLO"作为 printf 函数的输出。 Like this,像这样,

printf("%s",str);

Here we used str without asterisk.这里我们使用了不带星号的str

Why aren't we getting an address and instead getting "HELLO" as output here while we get address in case of pointers to integers when we use the pointer variable without asterisk?当我们使用不带星号的指针变量时,为什么我们没有获得地址,而是在此处获得“HELLO”作为输出,而在指向整数的指针的情况下获得地址?

Okay first of all int *p=5;好的,首先int *p=5; is wrong!是错的! you cant do that in the declaration of a pointer.你不能在指针的声明中做到这一点。 at That time the pointer expects an adress.那时指针需要一个地址。 You should do int *p;你应该做int *p; and then *p = 5;然后*p = 5; to assign the value to it.为其赋值。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM