2016-02-08 80 views
0

给定一个整数数组,我试图打印数组的所有零移动到数组的左侧。剩余数字的顺序无关紧要。对于在main中硬编码的数组,我总是会得到奇怪的输出,例如“{-1073741824,1049472,1,49,63,1055984,1}”。C:数组输出

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

所以,你定义一个数组。然后你定义另一个名为array的数组。然后你使用数组。但是,你在哪里使用或复制的价值? – AndASM

+0

为什么不使用简单的排序算法? –

+0

'malloc(0)'是未定义的行为...虽然您已经以有趣的方式使用它。 :)我怀疑这是你问题的根源。请注意,您实际上可能拥有从最小分配大小(8或16字节)返回的有效指针。任何时候调用malloc和realloc返回有效指针也是一个非常好的主意。 –

回答

2

您可以更换:

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

如果您使用此代码不需要mallocrealloc既不free

0

该代码看起来过于复杂 - 您不需要在使用%s时传递字符串,您可以直接打印它。所以

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

可以是:

print("{"); 

的第一步后,你可以只打印你发现零,然后通过加强和打印所有非零整数数量。有点像这样

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");