我试图得到一个字符串文字打印,但似乎有一些问题,它不给给予任何输出
#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++;
}
}
1条答案
按热度按时间nx7onnlm1#
不分先后
while(*p!= NULL);
。如果*p
开始等于NULL
,则循环永远不会运行。如果不是,p
永远不会更新,所以循环永远不会停止。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
编译程序会产生以下警告/错误。所有这些都将提供信息,并帮助您识别这些问题。我强烈建议你在编译器中打开警告。当你得到警告/错误时,养成修复第一个错误的习惯,然后重新编译。通常一个问题会产生其他问题,一个修复可以解决多个问题。