1

"I am trying to find the size of the 'list[34]' array but it is being set by random numbers when the program is being initialised. I cannot remove the rand() function in main because that is part of the question and is just added back in by the solution checker when I submit.

I have tried setting all the values in the array to '0' but that throws out the 'list_size' variable if the list is shorter than 35 values since the list is just filled with whatever is parsed into it followed by '0' in all other values.

#include <stdlib.h>
#include <float.h>

//  Declare Global variables here.
double list[34];
int list_size;

void array_stats() {
    //  Insert your solution here.

    for(int i = 0; i <= 35; i++)
    {
        scanf("%lf", &list[i]);

        list_size = i;
        if (list[i] == 0)
        {
            break;
        }
    }
}

#include <stdlib.h>
#include <time.h>

int main() {
// Simulate the test setup process.
    srand( time( NULL ) );
    for ( int i = 0; i < 34; i++ ) {
        list[i] = rand();
    }
    list_size = rand();

    // Call submitted code.
    array_stats();

    // Display contents of array list.
    for (int i = 0; i < list_size; i++) {
        printf("%f ", list[i]);
    }

    printf("\n");
    printf("Item count: %d\n", list_size);

    return 0;
}```

Expected result for an empty string (echo '' | file_name) is 0
Actual result for an empty string (echo '' | file_name) is 34
  • In your code: `for(int i = 0; i <= 35; i++)` you're using a wrong array length. Should be `for(int i = 0; i < 34; i++)` – Myst Aug 04 '19 at 04:33
  • Also, `for (int i = 0; i < list_size; i++)` might be out of bounds, since `list_size` is a random number (`list_size = rand();`) and it might be bigger then 34 (longer then the memory buffer). – Myst Aug 04 '19 at 04:34

1 Answers1

0

If you you whould have used int datatype in your array:

memset(arr, 0, sizeof(arr));

But since your are not, it get's a bit tricky and to clear a double array the best way is:

double list[34];
for (size_t i = 0; i < list; ++i)
  arr[i] = 0.0;

Theoretically, you should be safe using memset for floats and doubles, but see the caveats in the answers at Is it legal to use memset(,0,) on array of doubles? in case you have a non-standard floating point implementation.

Barr J
  • 10,636
  • 1
  • 28
  • 46
  • It is coming up with a segmentation fault if I try your second solution – Callum McNeilage Aug 04 '19 at 04:32
  • 2
    @BarrJ - I think you meant `(size_t i = 0; i < sizeof(list)/sizeof(list[0]); ++i)` .. or `for (double *p = list; p < *((&list)+1); ++p) *p = (double)0.0;` – Myst Aug 04 '19 at 04:36