Error accessing pointer

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 rotate. I ran the debugger and pointed out that the error is where the arrow points.

My goal is for my pointer from a vector to point to another dynamic memory to store only a int .

What am I doing wrong?

    
asked by anonymous 23.09.2014 / 13:26

2 answers

1

With this statement

int** items[5];

In fact, you are declaring an array of 5 elements which are pointers to pointers. I honestly do not understand why you need such a complicated thing.

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 a lot about what you are doing in this statement:

*items[i] = new int;

What is items[i] ? Pointer.

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

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.
    
23.09.2014 / 15:29
0

I do not see the point in you declaring a variable as a pointer and setting the vector size statically (that is, in the variable declaration itself).

Instead of doing this:

  int ** items[5];

You should do this:

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

And instead of doing this:

 *items[i] = new int;

You should do this:

 items[i] = new int;
    
23.09.2014 / 16:06