TyCharm February 2016

C: Array output

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;
}

Answers


Martín Muñoz del R&# February 2016

You can replace:

int *array = malloc(0);
for (int j = 0; j < count; ++j)
{
    array = realloc(array, (j + 1) * sizeof(int));
    array[j] = 0;
}

With something like:

int array[10]; //malloc(0);
int j = 0;
for (j = 0; j < count; ++j)
{
    array[j] = 0;
}

for (j = 0; j < n; ++j)
{
    if(a[j]!=0)
        array[count++] = a[j];
}

If you use this code you don't need malloc, realloc neither free.


user2612740 February 2016

The code looks overly complicated - you don't need to pass a string in using %s you can just print it directly. So

printf("%s", "{");

can be:

print("{");

After your first step, you could just print the number of zeros you've found, followed by stepping through and printing all the non-zero integers. Something a bit like this

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;
    }
}
printf("{");
for(int i=0; i < count; i++)
{
     printf("0,");
}
for(int i=0; i < n; i++)
{
     if (a[i]!=0) {
         printf("%d", a[i]);
         if (i < n-1) {
             printf(",");
         }
     }
}
printf("}\n");

Post Status

Asked in February 2016
Viewed 3,752 times
Voted 12
Answered 2 times

Search




Leave an answer