Home > front end >  Is it possible in C to assign pointer to an array or change to address of array to the pointer addre
Is it possible in C to assign pointer to an array or change to address of array to the pointer addre

Time:09-29

I need to assign pointer returning function to an array, is it possible?

#include <stdio.h>
int * arrayReturn(int *q){ // example function
    return q;
}
int main()
{
    int z[3] = { 1 , 2 , 3};
    int q[3];
    q = *(int [3]) arrayReturn(z); 
    printf("%d %d %d", q[0],q[1], q[2]);

    return 0;
}

This below code is close to what I want, but this is not an array anymore.

int (*c)[3] = (int(*)[3])arrayReturn(z); 
printf("%d %d %d", c[0][0],c[0][1], c[0][2]);

CodePudding user response:

A pointer is a variable which contains an address of memory. Array is just a place in the memory that occupies so many bytes. As a result, they are very different objects and cannot be assigned to each other.

However, a pointer can be used to point to an array and as a result can be used in copying data from one array to another, for example, using memcpy.

int c[3];
memcpy(c, arrayReturn(z), sizeof(c));

Of course, there is no checking of array sizes done and it is assumed that the size of an array to which points the return of the arrayReturn() is big enough to be copied to c. Neither there is a way to find out about the size of the array which it points to.

CodePudding user response:

No, you cannot reassign an array as you do here:

int q[3];
q = *(int [3]) arrayReturn(z); 

If you want to copy the contents of z to q, you can do that with the memcpy library function:

memcpy( q, z, sizeof z );

but the = operator isn't defined to copy array contents.

Otherwise, the best you can do is declare q as a pointer and have it point to the first element of z:

int *q = z; // equivalent to &z[0]

Unless it is the operand of the sizeof or unary * operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted, or "decay", to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array - that's why the above assignment works.

Arrays in C are simple sequences of elements - there's no metadata indicating their size or type, and there's no separate pointer to the first element. As declared, the arrays are

    --- 
z: | 1 | z[0]
    --- 
   | 2 | z[1]
    --- 
   | 3 | z[2]
    --- 
    ...
    --- 
q: | ? | q[0]
    --- 
   | ? | q[1]
    --- 
   | ? | q[2]
    --- 

There's no separate object q to assign to.

  • Related