c++ - 关于C语言char*指针的问题
PHPz
PHPz 2017-04-17 15:25:53
0
6
900

代码如下:

#include<stdio.h>

int main(void)
 {
     char* p = "xxx";

    printf("%c",*p);
    return 0;
}

为啥一定要加*号才能正确显示字符串的第一个字符呢?
不是p指针存了这个字符串了吗?
本人刚学C没多久,请大神们解析得仔细点,谢谢

PHPz
PHPz

学习是最好的投资!

reply all(6)
左手右手慢动作

First of all, I suggest you use an editor to debug, put a breakpoint on the printf line, and then look in the monitor to see what p and *p point to respectively.
Then, p is a character pointer type, pointing to the address of the first element of a character array, *p takes the value pointed to by p, which is the first element.
If you understand, you can think about the results of p++,*p++, and what is the value of p after the operation

大家讲道理

First of all, there is no such type of string in C. Strings in C are character arrays terminated by null characters.
Then, the p pointer saves not the string, but the head of the character array. The address of the element.
So you can use the indirect operator * to read the value in this address, which is the first element of this character array.

巴扎黑

Because the type of p here is a pointer, the string xxx is stored in the memory address it points to. If you use p directly, the output is the memory address pointed to by p. Add an * in front of it to output The content pointed to by this pointer.

小葫芦

First of all, p is a pointer type, which stores an address, and this address is index, which can be understood as the address of the first character of the entire string (actually not a string) , similar to the first element in an array. *This symbol refers to defining a pointer variable when it is defined, and when it is called, it takes the value in the address.
printf("%c",*p);, if you don’t add * to your statement, it means that what you output is the value of p, but the value of p is an address, so you will naturally not get the p address. The value that actually exists. By adding *, you can get the value stored at this address.

Ty80

You can also add "*" without adding it. You can also use array subscript to output the first character

printf("%c",p[0]);
迷茫

p is a pointer type. It stores the address pointing to the element. If is not added, the specific address is printed. After adding the sign, it is the element pointed to

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template