What is the difference between char a[] = ?string?; and char *p = ?string?;?

前端 未结 8 1028
太阳男子
太阳男子 2020-11-22 07:43

As the heading says, What is the difference between

char a[] = ?string?; and 
char *p = ?string?;  

This question was asked to me in inter

8条回答
  •  悲&欢浪女
    2020-11-22 08:20

    C and C++ have very similar Pointer to Array relationships...

    I can't speak for the exact memory locations of the two statements you are asking about, but I found they articles interesting and useful for understanding some of the differences between the char Pointer declaration, and a char Array declaration.

    For clarity:

    C Pointer and Array relationship

    C++ Pointer to an Array

    I think it's important to remember that an array, in C and C++, is a constant pointer to the first element of the array. And consequently you can perform pointer arithmetic on the array.

    char *p = "string"; <--- This is a pointer that points to the first address of a character string.

    the following is also possible:

    char *p;
    char a[] = "string";
    
    p = a; 
    

    At this point p now references the first memory address of a (the address of the first element)

    and so *p == 's'

    *(p++) == 't' and so on. (or *(p+1) == 't')

    and the same thing would work for a: *(a++) or *(a+1) would also equal 't'

提交回复
热议问题