数组之后的奇怪输出用C打印

时间:2014-09-13 17:34:33

标签: c output

我正在编写一个带三个数字的程序,第一个+第二个num是每行的长度,第二个num是行数,第三个是1或0.所以假设前两个数字是7和4如果第3个数字为1,我想按以下方式填充和打印数组:

10000000000
01000000000
00100000000
00010000000

但是当我打印它时,我的数组后面会出现奇怪的输出:

10000000000
01000000000
00100000000
00010000000
��1�
1�
��1

另外如果我在最后一个for循环中将putchar(arr [i] [j])更改为printf("%d",arr [i] [j]),我得到的输出是:

4948484848484848484848
4849484848484848484848
4848494848484848484848
4848484948484848484848
-63-1234849-12048700
0400049-964868-55
-41-6500004900016

有人可以解释为什么会发生这种情况以及我需要做些什么来获得干净的输出?

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

const char *byte_to_binary(int x)
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1)
    {   
        strcat(b, ((x & z) == z) ? "1" : "0");
    }   

    return b;
}

int main(int argc, char *argv[]) {

  char* tmp;
  int num1, num2, num3;
  int x = 128;
  int i, j;

  num1 = strtol(argv[1], &tmp, 10);
  num2 = strtol(argv[2], &tmp, 10);
  num3 = strtol(argv[3], &tmp, 10);


  int rlen = num1 + num2;  
  char arr[num2][rlen];

  memset(arr, '0', num2 * rlen); 

  // find out if the first number is a 1 or a 0.
  if ((num3 & x) == x) {
   arr[0][0] = '1';
  }
  else {
    arr[0][0] = '0';
  }

  for (i = 1; i < num1; i++) {
    for (j = 0; j < rlen; j++) {
      arr[i][i] = arr[0][0];
    }
  }

  for (i = 0; i < num1; i++) {
    for (j = 0; j < rlen; j++) {
      putchar(arr[i][j]);
    }
    putchar('\n');
  }

  return 0;
}

0 个答案:

没有答案