14

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.

1
  • 4
    Do you want a pointer to a literal array, or do you want to assign (i.e. copy) the content of the literal array to a dynamic array? Commented Jun 17, 2011 at 13:20

4 Answers 4

10

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, i.e.

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You dont need to init a with 4 elements, it will autoInit.
@RamonBoza: It will "autoInit" to 0 which isn't always what one wants
@RamonBoza... ah, you mean I needn't specify 4... yeah, I know, so what? :)
1

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

1 Comment

further note the following: char s = "Hello World" and char s[] = "Hello World" are radically two different things. In the first case s is of type char and hence a pointer and it is pointing to the read only memory location which holds "hello word" but in the second case s is an array of char and holds the address of the first memory location which contains this array.
0

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};

1 Comment

this doesn't work for me. I get the error "expected ';' at end of declaration". It expects ; after the new int[3], so it doesn't accepts the values initialization
-5

Use the following code, grid is a pointer, grid[] is an element of that pointer.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.