Home  >  Q&A  >  body text

c++ - 所有指针都是放在栈中吗

所有指针都是放在栈中吗,比如函数内局部指针变量、指向动态申请的对象的局部指针变量?

怪我咯怪我咯2714 days ago785

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:36:55

    What you said函数内局部指针变量、指向动态申请的对象的局部指针变量

    int test = 0; //全局静态存储区
    int* ptrTest = &test; // 这个指针自己也是在全局静态存储区上,指向的内存地址也是。
    
    int main()
    {
        int a = 2;//栈上
        int* ptr = &a;//ptr是在栈上,然后它指向的内存地址也是栈上的
    
        int* ptrHeap = new int(2);
        // new是在堆上申请的内存,返回的是这个申请的内存的地址
        // 然后ptrHeap是指向这个地址的,但是ptrHeap它自己是占的栈上的地址。
        delete ptrHeap;
    
        return 0;
    }
    

    The pointer itself occupies memory space, and then it points to other memory spaces.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:36:55

    Yes, pointing to the heap address

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:36:55

    Function pointer variables themselves are not all stack variables.

    Example:

    int ** p = new int*;

    For this example, p is a pointer to a pointer, p is also a pointer, and p points to a memory block that stores an int value. However, the memory that stores the pointer variable *p itself is the heap.

    It can be seen that pointer variables are the same as ordinary variables, they can be stack variables or heap variables.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 14:36:55

    Definitely not. Pointers are also variables, no different from other variables. Think about vector<int*>

    reply
    0
  • Cancelreply