Error accessing pointer

Asked

Viewed 84 times

1

int main()
{
    int**items[5];
    for (int i=0;i<5;i++)
    {
        *items[i] = new int; <--
    }
    return 0;
}

The program compiles, but does not run. I Debugger and pointed out that the error is where the arrow points.

My goal is that my one vector pointer points to another dynamic memory to store only one int.

What am I doing wrong?

  • 2

    take an asterisk from the item declaration. what Voce is doing and allocating a 5-position vector with pointers to other vectors. then a 3-dimensional matrix.

  • What error does the debugger indicate?

2 answers

1

With this statement

int** items[5];

in reality, you are declaring an array of 5 elements which are pointers to pointers. I honestly don’t understand why you need something this complicated.

What I think you need is simply an array of pointers

int* items[5]; // array de 5 ponteiros

or the pointer to other pointers.

int** items; 

Think about what you’re doing with this instruction:

*items[i] = new int;

What is items[i]? Pointer.

What happens if you un-reference a pointer? You access the pointed memory, but in your case there is no allocated memory. To allocate memory to the second level pointer you have to first allocate memory to those of first. What you have to do first is to allocate memory for the array pointers and only then for the pointers that the pointers of the pontoon array.

int** array[2];
array[0] = new int*; // alocar memoria para um ponteiro que ponta a um ponteiro
*array[0] = new int; // agora podes alocar memoria para o ponteiro de segundo nivel.

0

I see no sense in you declaring a variable as a pointer and fixing the size of the vector statically (i.e., in the variable’s own statement).

Instead of doing this:

  int ** items[5];

You must do this:

  int ** items = new int*[5];

and instead of doing it:

 *items[i] = new int;

You must do this:

 items[i] = new int;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.