给定一个整数数组,我尝试打印该数组,并将所有零移动到数组的左侧。其余数字的顺序无关紧要。对于在 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];
}
如果您使用此代码,则不需要 malloc
、realloc
和 free
。
关于C:数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281402/