0
votes
int get_first(int arr[],int count)
{

   int half = count / 2;

   int *firstHalf = malloc(half * sizeof(int));
   memcpy(firstHalf, arr, half * sizeof(int));
   return firstHalf;
}

int get_second(int arr[], int count)
{
    int half = count / 2;

    int *secondHalf = malloc(half * sizeof(int));
    memcpy(secondHalf, arr + half , half * sizeof(int));
    return secondHalf;
}

int result = get_first(arr, count);
int size = sizeof(result) / sizeof(result[0]);

i am writing a function that split an array into two equal parts. the function takes in an array and the size of the array. I am testing the function by storing the first half of the array in the result and print its length. But when I build the function, the line

int size = sizeof(result) / sizeof(result[0]);

gives an error says "error: subscripted value is neither array nor pointer"

Is it because my function failed to pass the first half of the array into result? or the way of storing an array is wrong? If so, how do I split the array, can someone help me to fix it? thanks in advance.

1
int result means that result is a scalar, so you can't do result[0], which assumes result to be an array or a pointer. - 500 - Internal Server Error
Your functions probably need to return a pointer (int *get_first(…), int *get_second(…)), but there are problems with how the calling code knows the size of the half that it gets back. You're likely to need to rethink this quite a lot. - Jonathan Leffler
@ Jonathan Leffler Right now I am just struggling with split the array into two parts, does it looks like my function is correct? I also tried to print the value of result[0] but it still failed. - zhangdi
@ 500 - Internal Server Error So how do I get the value in the result? I tried to print result[0] but it failed. - zhangdi
What do you expect to happen if you write something like 42[0], zhangdi? - autistic

1 Answers

0
votes

There are two problems that I can see:

  1. In functions int get_first(int arr[],int count) and int get_second(int arr[], int count) you are returning int pointers but functions' return type are int.
  2. result is declared as int but you are accessing it like result[0].

Correction for 1 is obvious from point 1 above. Correction for 2:

Instead of:

int result = get_first(arr, count);

You should write:

int *result = get_first(arr, count);

Hope this helps.