Home > Software engineering >  How to assign Pointer to an Array, to a new Array?
How to assign Pointer to an Array, to a new Array?

Time:06-28

I got this code:

#include <stdio.h>
#include <string.h>
int main(void)
{
int a[3]={1,2,3},
    b[3];
int (*p)[3]= &a;

b = p;

for(int i=0;i<3;i  )
    printf("%i",b[i]);
}

-I wanted output to be like "123", but I am having problems assigning the b array to what the p is pointing.

ps - memcpy( b, p, sizeof(b)); does just what i want but i want to do it without the use of that function.

CodePudding user response:

The line

b = p;

has a couple of problems. First of all, array expressions may not be the target of the = operator; you can't assign an entire array in a single operation like that1.

Secondly, the types don't match; p has type int (*)[3], while b has type int [3]. Arrays are not pointers - array expressions "decay" to pointer expressions under most circumstances, but in this case even the pointers would be of incompatible types (b would decay to an expression of type int *, not int (*)[3]).

No, the only ways to copy the contents of one array to the other are to use library functions like memcpy or to use a loop to assign each element individually:

for ( size_t i = 0; i < 3; i   )
  b[i] = (*p)[i]; // or b[i] = a[i]

That's it.


  1. Initialization is different from assignment.

CodePudding user response:

Arrays do not have the assignment operator. You need somehow to copy elements of one array to another array.

Without using the standard function memcpy you can use an ordinary loop as for example

for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i   )
{
    b[i] = a[i];
}

Or if to use intermediate pointers you can write

for ( int *p = a, *q = b; p != a   sizeof( a ) / sizeof( *a );   p )
{
    *q   = *p;
}

CodePudding user response:

You have a small fixed size array, perfectly suitable for wrapping inside a struct, so you can do this:

#include <stdio.h>
#include <string.h>

struct ia3 {
    int data[3];
}

int main(void)
{
    struct ia3 = {{1,2,3}};
    struct ia3 b;
    struct ia3 *p = &a;
    
    b = *p; // struct assignment
    
    for(int i=0;i<3;i  ) {
        printf("%i",b.data[i]);
    }
}

CodePudding user response:

"...but i want to do it without the use of [memcpy(,,)]."

It is unclear why using memcpy() is not agreeable in this exercise, but it does do the task more efficiently then loop for large array sizes.

If you just want a pointer to the array...

int a[3]={1,2,3};
//create pointer
int *b = a;//does not copy array a, just points to it   

//If an additional array is needed, do this...
int b[3] = {0};
int i = 0;

//to copy, without memcpy(), use this alternative.
for(i=0;i<3i  ) b[i] = a[i];//makes copy of array a

for(i=0;i<3;i  )
   printf("%i",b[i]);
  • Related