我需要为初始化指针分配内存吗?

use*_*400 1 c c++ pointers memory-management

int a = 10;    
int *p = &a; 

*p = 20;  /* Is this a valid statement? */
Run Code Online (Sandbox Code Playgroud)

我明白,如果我这样做int *p;,如果我这样做*p = 10,它是无效的,因为我没有分配任何内存p.但是,我想知道是否初始化指向某个地址的指针是否为该指针分配内存?

Shi*_*dim 6

我想知道是否初始化指向某个地址的指针是否为其分配内存?

它不分配任何内存.因为p一个指向一个已分配的内存

int a = 10;    // a is statically allocated and value 10 is assigned.
int *p = &a;  // p is pointed to address of a. 
*p = 20;  // at this point p points to that statically allocated memory
Run Code Online (Sandbox Code Playgroud)


Omk*_*ant 5

int a = 10;    
int *p = &a; 

*p = 20;  /* Is this a valid statement? */
Run Code Online (Sandbox Code Playgroud)

答案就是YES这个特例.

但是当你喜欢这样的时候:

int *ptr;  //declaration of pointer variable
*ptr = 20;  // It means you are assigning value 20 to the variable where `ptr` points to.
Run Code Online (Sandbox Code Playgroud)

但实际上ptr并没有指向任何地方,基本上它意味着它有indeterminate value.

这样做*ptr = 20会将值20放到指向的内存地址ptr.所以它被称为Undefined bahavior

在你的情况下,它是有效的,因为它&a是有效的内存位置,并p在我们这样做时开始指向该变量p= &a.

所以*p = 20意味着实际更改或指定a使用指针的值p.