Jacob Hempel
Jacob Hempel

Reputation: 37

Assign local array's contents to global static array's contents?

I have a couple static global arrays, and I need to conditionally set an array inside my function to be equal to one of them under certain conditions.

static int arr1[] = {1,2,3,4};
static int arr2[] = {4,3,2,1};

int myFunc(int x) {
    int myArr[4];
    if (x > 4) {
        myArr = arr1;
    }
    else if (x <= 4) {
        myArr = arr2;
    }
}

I'm getting error: incompatible types in assignment and the only thing I can guess is that the static keyword is interfering, because as far as I can tell, both sides of the assignment are int[].

Thanks in advance!

Upvotes: 0

Views: 46

Answers (2)

sg7
sg7

Reputation: 6298

One easy way is to use a pointers to the static global arrays. The name of the array is a pointer. Then your function int myFunc(int x) looks almost as your original one.

This is a sample code:

#include<stdio.h>

static int arr1[] = {1,2,3,4,5,6};
static int arr2[] = {4,3,2,1};

int myFunc(int x) {
    int *myArr;
    size_t i;
    size_t myArrSize;

    if (x > 4) {

        myArr = arr1;
        myArrSize = sizeof(arr1)/sizeof(int);
    }
    else if (x <= 4) {

        myArr = arr2;
        myArrSize = sizeof(arr2)/sizeof(int);        
    }

    for(i=0; i< myArrSize; i++)
        printf("array[%d]=%d\n", i , myArr[i]);

     printf("\n");
}

int main() {

   myFunc(6);
   myFunc(4);

   return 0;
}

Output:

array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
array[5]=6

array[0]=4
array[1]=3
array[2]=2
array[3]=1

As you can notice the sizes of arr1 and arr2 can be different.

Upvotes: 0

lvella
lvella

Reputation: 13443

One way to do it is:

static int arr1[] = {1,2,3,4};
static int arr2[] = {4,3,2,1};

int myFunc(int x) {
    int myArr[4];
    if (x > 4) {
        memcpy(myArr, arr1, sizeof arr1);
    }
    else if (x <= 4) {
        memcpy(myArr, arr2, sizeof arr2);
    }
}

But maybe you just need a pointer to the global array (if you aren't going to modify the copy, perhaps that is your case), so you can just store a pointer:

int myFunc(int x) {
    const int* myArr;
    if (x > 4) {
        myArr = arr1;
    }
    else if (x <= 4) {
        myArr = arr2;
    }
}

Upvotes: 1

Related Questions