0

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!

2 Answers2

1

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;
    }
}
lvella
  • 12,754
  • 11
  • 54
  • 106
  • I actually used the pointer solution the first time around, but got a segfault due to another issue. I'll accept your answer because it would have fixed my problem, if my problem was what I thought it was. – Jacob Hempel Feb 15 '18 at 14:47
0

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.

sg7
  • 6,108
  • 2
  • 32
  • 40