C语言 有人能帮忙找出这个程序失败的原因吗

rhfm7lfc  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(76)

我试图得到一个字符串文字打印,但似乎有一些问题,它不给给予任何输出

#include <stdio.h>

int main() 
{
    char *device_name = "mychardev";
    void test_pointer(device_name);
    return 0;
}

void test_pointer(char *p)
{
    while(*p!= NULL);
    { 
        printf("%s",*p);
        p++;
    }
}
nx7onnlm

nx7onnlm1#

不分先后

  • While循环:结尾的后缀表示你的while循环是d justwhile(*p!= NULL);。如果*p开始等于NULL,则循环永远不会运行。如果不是,p永远不会更新,所以循环永远不会停止。
  • while循环正在测试的条件将char值与更大的整数类型NULL进行比较。为了避免可能出现的问题,请与null字符本身进行比较:while (*p != '\0')
  • 您在main中对test_pointer的 * 调用 * 不需要void。就像test_pointer(device_name);一样,这看起来像是main内部的函数声明,但没有device_name的类型。
  • 您在test_pointer中对printf的调用使用了错误的格式说明符。您正在解引用p,这会给您一个char值,因此使用%c而不是%s。当需要字符串时传递char会产生未定义的行为。
  • main中调用test_pointer之前,您尚未进行前向声明。

使用gcc和-Wall -Wextra -Werror编译程序会产生以下警告/错误。所有这些都将提供信息,并帮助您识别这些问题。我强烈建议你在编译器中打开警告。
当你得到警告/错误时,养成修复第一个错误的习惯,然后重新编译。通常一个问题会产生其他问题,一个修复可以解决多个问题。

test3.c: In function ‘main’:
test3.c:6:5: error: parameter names (without types) in function declaration [-Werror]
     void test_pointer(device_name);
     ^~~~
test3.c:5:11: error: unused variable ‘device_name’ [-Werror=unused-variable]
     char *device_name = "mychardev";
           ^~~~~~~~~~~
test3.c: In function ‘test_pointer’:
test3.c:12:13: error: comparison between pointer and integer [-Werror]
     while(*p!= NULL);
             ^~
test3.c:12:5: error: this ‘while’ clause does not guard... [-Werror=misleading-indentation]
     while(*p!= NULL);
     ^~~~~
test3.c:13:5: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘while’
     {
     ^
test3.c:14:18: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Werror=format=]
         printf("%s",*p);
                 ~^  ~~
                 %d
cc1: all warnings being treated as errors

相关问题