简体   繁体   中英

Pointers (to pointers) and new/malloc vectors (inside of vectors) c++

How do pointers work with arrays? I find the syntax a bit of a mystery, example (16x1):

int* a = new int[16];
a[16] = 33;
cout << a[16] << endl;

The above example works. Usually * needs to be in front of a pointer to write/read the value, but not with vectors?

The case is more complicated for multidimensional arrays, which I found the following a way to create (16x3):

int** a = (int**)new int[16];
for (int i = 0; i < 16; i++)
{
    a[i] = (int*)new int[3];
}
a[15][2] = 4;
cout << a[15][2] << endl;

Again, the above works, but it's hard to grasp how the syntax relates to pointers. The syntax also works with malloc. With malloc there is an option "memset" which automatically initializes the multidimensional array (put in the for loop). Is there similar option with new?

Usually * needs to be in front of a pointer to write/read the value, but not with vectors?

You always need to dereference a pointer to get the pointed value. The subscript operator is just another way to dereference it. a[b] is equivalent to *(a+b) (unless a is a class with overloaded subscript operator).


 int** a = (int**)new int[16]; 

This is a bug. You've allocated an array of int , but try to point to first element as if it was an int* . If you want an array of pointers, then you must specify the correct type ( int* ) in the new-expression. A way to avoid bugs like this is to never ever cast the return value of new . Then the compiler will tell you when you make a mistake.

Again, the above works

The behaviour is undefined.

With malloc there is an option "memset" which automatically initializes the multidimensional array (put in the for loop). Is there similar option with new?

memset is in C++ standard library as well, but you don't need it for initialization. Simpler is to use value initialization. Also note the correct type and lack of casting:

int** a = new int*[16]();
//                    ^ syntax for value initialization

PS You don't deallocate the memory that you allocated. Therefore you leak the memory.

PPS It is a bad idea to store pointeres to dynamic objects in bare pointers. It's better to use a RAII container like std::vector .

This syntax works because operator[], called offset operator, works just the same as operator*, but increments the pointer by some amount. So a[5] is just the same as *(a+5) .

If you want to learn a little bit more about it I would suggest checking article about pointer , where they also mention this operator and provide more technical explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM