Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Initialize array pointer

How do I initialize a pointer to a literal array?
I want *grid to point to the new allocated int array {1, 2, 3}.

int *grid = new int[3];
*grid = {1, 2, 3};

thank you.

like image 995
somewho3 Avatar asked Jun 17 '11 13:06

somewho3


People also ask

What is array of pointers how it is initialized in C?

An array of pointers is useful for the same reason that all arrays are useful: it lets you numerically index a large set of variables. Below is an array of pointers in C that points each pointer in one array to an integer in another array. The value of each integer is printed by dereferencing the pointers.

Can we declare pointer array in C?

C. In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.

Can I declare array as pointer?

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]. In the above example, p is a pointer to double, which means it can store the address of a variable of double type.


1 Answers

@above grid points to the address location where the first element of the array grid[] is stored. Since in C++ arrays are stored in contiguous memory location, you can walk through your array by just incrementing grid and dereferencing it.

But calling grid an (int*) isnt correct though.

like image 103
Amm Sokun Avatar answered Oct 07 '22 18:10

Amm Sokun