is there a way to convert from pointer array to array

I tried the following, but it doesn't work.

int[]a={1,2,3};
int* p;
p=a;
a=(*P);// doesn't work

Recommended Answers

All 4 Replies

Your question is not in clear English, but I think you mean "Is there a way to convert an array to a pointer, or a pointer to an array".

An array is a pointer (to the zero-th element), so there's no way to convert. Just use it as is. Your code is confused because you use P and p as if they were the same (they are not) and you overwrite a twice.

If you have a pointer to array, you can use it as an array...

int main()
{
        int a[]={1,2,3};
        int* p=a;
        int val=p[0];
}

An array is a pointer (to the zero-th element)

No, an array is not a pointer. An array name when used in value context will be converted to a pointer to the first element, but this conversion does not take place in an object context. You can verify that this is the case by using an array and a pointer in object context and checking the result:

#include <iostream>

int main()
{
    int a[] = {1,2,3,4,5};
    int *p = a;

    std::cout<< sizeof a <<'\n'<< sizeof p <<'\n';
}

If the array were really a pointer, sizeof would evaluate to the size of a pointer, not the total byte size of the array.

C++98 Standard Section 4.2 "Array-to-pointer conversion", paragraph 1:

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T.” The result is a pointer to the first element of the array.

As Narue said, arrays and pointers are not the same, however, the standard defines an implicit conversion from an array to an _rvalue_ pointer. An rvalue means that the variable cannot be assigned a value (i.e. it's "read-only", as in, it is usually on the right-side of an assignment, but cannot appear on the left-side (that requires an lvalue)). This is why you cannot, as in your example, do a = p; or something like that, because it would require a conversion of the array "a" into an lvalue pointer, which is not allowed, for obvious reasons.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.