Home > Back-end >  Assigning values to certain components of an array rather than the whole array
Assigning values to certain components of an array rather than the whole array

Time:12-18

When I want a function returning an array I can use pointers:

#include <stdio.h>
#include <stdlib.h>

int* integers(int size)
{
   int* integers_array=malloc(size*sizeof(int));
   for(int j=0; j<size; j  )
   {
      integers_array[j]=j;
   }
   return integers_array;
}


But what if, for example, I already have an array x and I want to assign new values to all its components except the first 2? I would like to do it with address arithmetic, but I cannot do the following

x 2=integers_array(4);

because I can't have an expression on the left hand side of an assignment. So far, the way I dodge the issue is to create an assignment void function:

void assignment(int size, int in_array[], int out_array[])
{
   for(int j=0; j<size; j  )
   {
      out_array[j]=in_array[j];
   }   
}

when I do this, the void function works with address arithmetic, meaning that I can do the following:

int main()
{
    int size=4;
    int* y;
    int x[]={1, 1, 1, 1, 1, 1};
    y=integers(size);
    assignment(size, y, x 2);
    return 0;
}

Is there a better way to do this? Without creating a void function. What is the proper syntax to assign values only to a portion of an array, from a function?

CodePudding user response:

… I can't have an expression on the left hand side of an assignment.

The left side of an assignment may be an expression, but it must be an lvalue, which x 2 is not.

To set n elements of array x starting at offset o elements from the beginning of the array to values from the same type of elements of array y (starting at the beginning of y), you can use memcpy:

memcpy(x o, y, n * sizeof *x);

If the movement is within the same array and may overlap, use memmove instead of memcpy.

Other than that, to change portions of an array, expect to write your own loops, whether you encapsulate them in a function or not. C is not a language designed to provide many compound functions or automatic management of complicated types.

  • Related