-1

A kyu on codewars asks for the following:

Complete the method which accepts an array of integers, and returns one of the following:

"yes, ascending" - if the numbers in the array are sorted in an ascending order "yes, descending" - if the numbers in the array are sorted in a descending order "no" - otherwise You can assume the array will always be valid, and there will always be one correct answer.

I put together the following but run into "Caught unexpected signal: SIGSEGV (11). Invalid memory access" when testing. Can someone please explain the error to me and what part of the script triggers it?

#include <stdio.h>

char* isSortedAndHow(int* array, int arrayLength)
{
  // Create an empty array where ascending or descending test results will be stored
  int results[] = {};
  int i;
    // If the value is greater than the previous one add a 1, if smaller add a 0, if equal, add 1000
    for (i = 1; array[i]; i++){
      if (array[i] < array[i-1]){
        results[i-1] = 0;
      } else if (array[i] > array[i-1]) {
          results[i-1] = 1;
      } else {
          results[i-1] = 1000;
      }
    }
  // Add the value of all values in the results array and return the answer
  int sum = 0;
  for (i=0; results[i]; i++) {
    sum = sum + results[i];
  } if (sum == 0) {
     return "yes, descending";
  } else if (sum == (arrayLength - 1)) {
     return "yes, ascending";
  } else {
       return "no";
  }
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 3
    `int results[] = {};` declares an array of zero size. – Retired Ninja Jun 06 '21 at 16:08
  • There's really no need for `results` at all. Just combine the loops. Instead of doing `results[i - 1] = some_value;` do: `sum += some_value;` where `some_value` will be 0, 1, or 1000. – Craig Estey Jun 06 '21 at 17:16
  • 1
    Your logic seems wrong. Consider the array with 1001 elements, the first 1000 of which are monotonically decreasing with an increase in the last element (eg, 1000,999,998,...1,2). Using a sum is a bad idea. Just compare each element in a simple state machine. – William Pursell Jun 06 '21 at 18:02
  • What answer should you give for an array of size 0, or size 1? – William Pursell Jun 06 '21 at 18:04
  • [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – Nate Eldredge Jun 07 '21 at 14:09

1 Answers1

1

The culprit is the line

    int results[] = {};

You declare an array of int with a size of zero. Further down the code you try to write into that array: BOOM!

One possible solution is to allocate the array with the size arrayLength. But as commenters said, you don't need this array at all. Rethink your algorithm.

the busybee
  • 10,755
  • 3
  • 13
  • 30