gpt4 book ai didi

c++ - 我需要为初始化的指针分配内存吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:05:16 24 4
gpt4 key购买 nike

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

*p = 20; /* Is this a valid statement? */

我知道如果我执行 int *p; 然后如果我执行 *p = 10 ,它是无效的,因为我没有分配任何内存给 p。但是,我想知道初始化指向某个地址的指针是否会为该指针分配内存?

最佳答案

I was wondering if initializing a pointer to some address allocates memory to it or not?

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

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

关于c++ - 我需要为初始化的指针分配内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13701389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com