C:字符到位并打印

C: Char to Bits and print

我编写了以下代码,通过函数 intToBits 将 char 转换为位数组:

typedef unsigned char poly8;
typedef unsigned long long poly8x64[8];

char* intToBits(unsigned k) {
    int i; 
    char *nk = malloc(8);
    for(i=7;i>=0;i--){        
        nk[i] = (k%2);        
        k = (int)(k/2);
        printf("nk= %d \n", nk[i]);
    }
    return *nk;
}

void poly8_bitslice(poly8x64 r, const poly8 x[64])
{
  //TODO
    int i;
    for(i=0;i<64;i++)
    {
        printf("x= %d \n", x[i]);
        char* mem = intToBits(x[i]);
        printf("bufer= %d \n", *mem);;
    }
}

int main()
{

  poly8 a[64], b[64], r[64];
  poly8x64 va, vb, vt;
  int i;

  FILE *urandom = fopen("/dev/urandom","r");
  for(i=0;i<64;i++)
  {
    a[i] = fgetc(urandom);
    b[i] = fgetc(urandom);
  }

  poly8_bitslice(va, a);
  poly8_bitslice(vb, b);

  fclose(urandom);
  return 0;
}

但是,在打印时我遇到了分段失败错误。我不知道该怎么办。指针不正确?我只想打印 intToBits 的结果。

罪魁祸首是 intToBits 中的这一行:

return *nk;

它 returns 是 char 而不是 char*,如果您打开编译器警告,编译器会通知您。

改为:

return nk;