-1

Is there actually array function in C? I actually wanted to return several integer value at one time. The code below is not valid obviously but it's just what I'm thinking about. Is there any other method to achieve this?

int marks[5] = {90, 90, 70 ,50, 40};
int search = 90;

int linearSearch(){
  int result[5];
  int index = 0;

  for(int i = 0; i < 5; i++){
     if(marks[i] == search){
        result[index] = i;
        index++;
     }

  }
  return result;
}
Cheang Wai Bin
  • 181
  • 1
  • 1
  • 9
  • No. Bury your array in a structure and return that. You need one anyway so the caller can know how many (if any) results you found (i.e. `index` can also be a member of said structure). – WhozCraig Nov 20 '19 at 03:47

3 Answers3

1

We can wrap the array in a struct.

#define MAX_N 32

typedef struct{
    int n;
    int result[MAX_N];
} Array;

Array linearSearch(){
    Array arr;
    //do something
    return arr;
}
Thach Pham
  • 98
  • 5
1

You declared result inside a function as a stack memory and you're returning its address. That address will not be valid after the function returns (The memory allocated for that function gets deallocated). Either declare it dynamically and return it's addresses or declare it in your calling function and pass it's address as argument to linearSearch() or you can even make it global just like you can for search

0

Now I realised this is a very stupid question but short answer, no. What I did is i declared a global array variable and then I pass the value into the array. With that I can call back the value in the array.

int marks[5] = {90, 70, 90 ,50, 40};
int search = 90;

//global variable
int result[5];
int count = 0;

void linearSearch(){
   for(int i = 0; i < 5; i++){
      if(marks[i] == search){
         result[count] = i;
         index++;
      }
   }
}

Now this should return 0 and 2 to the result[0] and result[1]. Just make sure to reset count to 0 later.

Cheang Wai Bin
  • 181
  • 1
  • 1
  • 9