search

Home  >  Q&A  >  body text

c++ - 关于C语言char*指针的问题

代码如下:

#include<stdio.h>

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

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

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

PHPzPHPz2813 days ago913

reply all(6)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 15:27:53

    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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 15:27:53

    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.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:27:53

    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.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:27:53

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:27:53

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

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

    reply
    0
  • 迷茫

    迷茫2017-04-17 15:27:53

    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

    reply
    0
  • Cancelreply