简体   繁体   中英

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.

You can't initialize a dynamically allocated array that way. Neither you can assign to an array(dynamic or static) in that manner. That syntax is only valid when you initialize a static array, ie

int a[4] = {2, 5, 6, 4};

What I mean is that even the following is illegal:

int a[4];
a = {1, 2, 3, 4}; //Error

In your case you can do nothing but copy the velue of each element by hand

for (int i = 1; i<=size; ++i)
{
    grid[i-1] = i;
}

You might avoid an explicit loop by using stl algorithms but the idea is the same

Some of this may have become legal in C++0x, I am not sure.

@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.

I'm not sure if this is obvious but you can do this in one line.

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

Since this is C++ we are talking about you can also split it into two files. Where your .h file contains:

int *grid;

And your .cpp file contains:

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

使用以下代码,grid 是一个指针,grid[] 是该指针的一个元素。

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

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