0

Is possible to assign pointer to array or array to array?

int arr[3] {1,2,3};
int pnt[3];
pnt = arr;
//or
pnt = &arr[0];

compiler don't want accept this....

4
  • 3
    There are no pointers in the shown code. The variable pnt is an array, not a pointer, and arrays can't be assigned to. Commented Apr 6, 2022 at 6:57
  • 1
    Perhaps the confusion is because arrays can decay to a pointer (to its first element)? That means plain arr in the right context will be equivalent to &arr[0], and that will have the type "pointer to int", or int *. But even with the decay, an array isn't a pointer. Commented Apr 6, 2022 at 6:58
  • Change int pnt[3]; to int* pnt; then both statements pnt = arr; and pnt = &arr[0]; will work. Commented Apr 6, 2022 at 7:11
  • Also, pnt = arr would work if they were std::vector<int>. Commented Apr 6, 2022 at 8:34

2 Answers 2

1

Is possible to assign pointer to array

Yes.

or array to array?

No. Arrays are not assignable.

compiler don't want accept this....

That's because pnt is not a pointer. You can create a pointer to the first element of the array like this:

int* pnt = arr;
Sign up to request clarification or add additional context in comments.

Comments

0

assign pointer to array

You can assign array to a pointer. E.g.:

int b[2] = {3,4};
int *p;
p=b;

Note, that in your case, you've tried to assign an array to another array, not a pointer. The variable p is still a pointer, but now happens to point to the place in memory, where the array b sits.

or array to array

No, you can't do this. You could use std::array if you want this kind of syntax. In case of the raw array, like in the example, you'd have to copy the data from one array to another.

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.