开发者

Pointer Memory Allocation Issue

Trying to allocate memory for the bobby array but it's not working. Why?

I expected the bobby pointer to be allocated for 5 spaces but when I run and look in local it only has one.

    #include "queue.h"
#include <iostream>

usin开发者_StackOverflow中文版g namespace std;

int main()
{
    // Create the queue
    CustomQueue* obj = new CustomQueue(5);
    int astar[100];
    int* bobby;
    bobby = new int[5];
    // Place numbers into the queue

    obj->push(50);
    obj->push(40);
    obj->push(30);
    obj->push(20);
    obj->push(10);


    return 0;
}


I think that maybe you are intending to do

int bobby[5];

then you will see all elements together in a debugger. Otherwise you see bobby as the pointer to the value, and in visual studio you will need to type something like bobby,5 to see all 5 elements.

if you are doing this statically, you may as well put it on the stack.

also

int bobby[5];
sizeof(bobby) = 20 (assuming 4 B/int)

but

int* bobby;
sizeof(bobby) = 4.


Your debugger (I'm assuming that's what you mean by "look in local") only knows that the bobby pointer is a pointer to a single integer. The debugger does not understand the following allocation new int[5]. This is due to the way pointers and arrays work in C++, and is not due to incorrect code on your part.

You may be able to instruct your debugger to display more following elements of the array you allocated, but the way to do that would be specific to whatever tools you're using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜