Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中打印未知字符,而不是破折号和空格_C_Pointers_Char - Fatal编程技术网

在C语言中打印未知字符,而不是破折号和空格

在C语言中打印未知字符,而不是破折号和空格,c,pointers,char,C,Pointers,Char,以下是我的代码的相关部分: //helper function that prints "------" lines or " " lines void li(char* a, int len) { int i; for (i=0; i<len; i++) { printf("%c",a); } } //helper function that prints out bar void bar(int le

以下是我的代码的相关部分:

//helper function that prints "------" lines or "      " lines
void li(char*  a, int len)
{
   int i;
      for (i=0; i<len; i++)
        {
          printf("%c",a);
        }
}

//helper function that prints out bar 
void bar(int length, int height)
{
     int i;
//prints out top line
     li("-", length);

//prints middle lines of spaces and "|"
     for (i=0;i<height-2;i++) {
     printf("\n");
     li(" ", 6);
     printf("|");
     li(" ", length-2);
     printf("|");
}
//prints bottom line
     if (height>=2){
     printf("\n");
     li(" ", 6);
     li("-", length);}
  return ;
}
实际产量

The: ��������������
     ������|�������������|
     ���������������������
^^这些应该是未知字符


无论如何,我试图解决这个问题,但迄今为止都没有成功。发生这种情况的原因是什么?

您想打印角色本身。将字符传递给它,而不是
char*

  printf("%c", *a);

问题在于您理解字符和字符串的方式。 要解决此问题,可以更改li()的签名。定义应该是

void li(char  a, int len)
{
   int i;
      for (i=0; i<len; i++)
        {
          printf("%c",a);
        }
}
输出:

-----
      |   |
      |   |
      |   |
      -----GGGGG
您可以对代码进行更改,使其按您想要的方式打印。
希望这能有所帮助。

当它需要一个
char
时,将
char*
传递到
printf
是未定义的行为,很可能会导致这种行为。
printf(“%c”,*a)
缺少
*
?@Als:应该是
a[i]
,而不是
*a
//helper function that prints "------" lines or "      " lines
void li(char  a, int len)
{
   int i;
      for (i=0; i<len; i++)
        {
          printf("%c",a);
        }
}

//helper function that prints out bar 
void bar(int length, int height)
{
     int i;
//prints out top line
     li('-', length);

//prints middle lines of spaces and "|"
     for (i=0;i<height-2;i++) {
     printf("\n");
     li(' ', 6);
     printf("|");
     li(' ', length-2);
     printf("|");
}
//prints bottom line
     if (height>=2){
     printf("\n");
     li(' ', 6);
     li('-', length);}
  return ;
}
main()
{
bar(5,5);
li('G',5);

}
-----
      |   |
      |   |
      |   |
      -----GGGGG