C:数组输出

标签 c arrays

给定一个整数数组,我尝试打印该数组,并将所有零移动到数组的左侧。其余数字的顺序无关紧要。对于在 main 中硬编码的数组,我不断收到奇怪的输出,例如“{-1073741824,1049472,1,49,63,1055984,1}”。

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

最佳答案

你可以替换:

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

用类似的东西:

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

如果您使用此代码,则不需要 mallocreallocfree

关于C:数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281402/

相关文章:

php - 从数组中插入多行到数据库

c++ - 回调 g_source_set 回调总是被调用?

c - typedef 中的动态二维数组

c++ - gcc - 将多个 c 文件链接到一个 c++ 文件

PHP:有没有一种简单的方法可以将数字列表(作为字符串,如 "1-3,5,7-9")解析为数组?

javascript - 按升序对数组进行排序,同时消除重复值

c - 初始化结构变量时出错?

C 嵌套 union 和结构

java - 此标记后预期的表达式

Javascript - EXTjs 访问数组值