0

Im trying to debug why my helpers.c in the find pset is not working perfectly. I kept getting random large numbers in my array and I kept going up the ladder in the function to the point of initialising the array.

int max = 0;
for (int i = 0; i < n; i++)
{
    if (values[i] > max)
    {
        max = values[i];
    }
}

// Declare variables
int * count_arr = malloc(max);
for (int j = 0; j < n; j++)
{
    printf("%d ", count_arr[j]);
}
printf("\n");

As you can see, I try to find the max value of the given array and then declare an empty array up to the maximum number in the array. The second for loop is just so I can debug the results which are 0 0 0 0 0 0 135137 0 0 when given int values[9] = {3,4,1,5,9,7,8,6,2} as input. Can anyone please help me figure out why there is that random number there?

1

In the description for malloc, note the following sentence:

DESCRIPTION

Allocate size bytes of memory. Unlike calloc, malloc will not pre-set all allocated memory to zero.

This tells you what's happening (memory allocated by malloc can contain any values), and it also presents one way to fix this.

Now to the specific dimensions. You probably would want to use like

int * count_arr = calloc(max + 1, sizeof(int));

creating the space for an array containing max + 1 elements, the largest of which has index max. Using calloc instead of malloc saves you from setting all the elements to 0 manually in a loop.

You could alternatively do int count_arr[max + 1] = {0};, creating the array on stack instead of heap.

You then would have to use a loop over your values array, running from 0 to <n, incrementing the count_arr[values[i]].

Make sure to run any index you directly pass to count_arr from 0 to <=max, not to <n.

If you used malloc or calloc, don't forget to free the space after use.

1
  • Yes! This is exactly what I was just looking at. Thank you very much. – Tod Lazarov May 16 '17 at 21:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .