Given an integer array, I'm trying to print the array with all the zeros moved to the left of the array. The order of the remaining numbers doesn't matter. I keep getting strange outputs like "{-1073741824,1049472,1,49,63,1055984,1}" for the array that is hardcoded in main.
int main(int argc, const char * argv[]) {
int a[10] = {3, 0, 1, 4, 0, 0, 7, 20, 1, 5};
int n = 10;
int count = 0;
for (int i = 0; i < n; ++i)
{
if (a[i] == 0)
{
++count;
}
}
//////////
int *array = malloc(0);
for (int j = 0; j < count; ++j)
{
array = realloc(array, (j + 1) * sizeof(int));
array[j] = 0;
}
//////////
printf("%s", "{");
for (int k = 0; k < n-1; ++k)
{
if (array[k] != 0)
{
printf("%d%s", array[k], ",");
}
}
printf("%d", array[n-1]);
printf("%s", "}\n");
//////////
free(array);
return 0;
}
malloc(0)is undefined behavior... Though you've certainly used it in an interesting way. :) I doubt it's the source of your problem. Take note that you may actually have a valid pointer returned from that of a minimum allocation size (8 or 16 bytes). It's also a super good idea to check that malloc and realloc return valid pointers any time they are called.printf()statements.