gpt4 book ai didi

c - 当 char * 被类型定义并通过结构访问时,为什么编译器会发现 char * 和 printf 的转换说明符 "s"不匹配?

转载 作者:太空狗 更新时间:2023-10-29 15:41:36 25 4
gpt4 key购买 nike

为什么编译器会提示以下 printf 中的参数类型“char”和转换说明符“s”不匹配?

#include <stdio.h>
#include <stdlib.h>
typedef char * STR; // causes problems in printf below
int main(void) {
struct MyStruct {
STR str;
};
struct MyStruct ms = {"some text"};
printf("%s\n", ms.str);
return (EXIT_SUCCESS);
}

当删除 typedef 时,编译器对相同的代码没有任何提示:

#include <stdio.h>
#include <stdlib.h>
//typedef char * STR; // runs fine without typedef
int main(void) {
struct MyStruct {
char * str; //STR str;
};
struct MyStruct ms = {"some text"};
printf("%s\n", ms.str);
return (EXIT_SUCCESS);
}

注意事项:

  • 系统 = Win 64、NetBeans IDE 8.2、GCC 编译器,无论是使用 Cygwin 还是 MinGW 工具,无论是 32 位还是 64 位,都没有区别。

  • 如果我避免使用 struct 或 typedef,就会消除错误。但是,如所示,只要同时使用 typedef 和 struct,就会出现错误。

  • 在发布之前,我检查了(除其他外)stackoverflow.com/questions/20944784/,它建议使用 const。但是,无论 typedef 是否为

    指向常量 char 的指针 (typedef char const * STR);指向 char 的常量指针 (typedef char * const STR);或者指向常量 char 的常量指针 (typedef char const * const STR);

  • 逐字错误消息:参数类型“char”与转换说明符“s”不匹配。

  • 进一步的测试表明 ms.str 确实是预期的类型 char *(例如,正确的 sizeof,将转换说明符交换为“c”以表示 char,如错误消息所示,如果 printf '将指向 char 的指针作为 char 等)

  • 更改 typedef 标识符的名称(例如,从 STR 到 STR_TEST)会导致相同的错误。因此似乎与标准 header 中的定义没有冲突。

最佳答案

在这个问题的评论回声室中,那些参与者和 OP 似乎已经达成共识,这是 NetBeans 的错。

I cannot reproduce your problem on Cygwin x64. Furthermore, "Mismatching the argument type "char" and conversion specifier "s"" doesn't look like a GCC warning, is probably a Netbeans issue. See also this similar Netbeans bug report – RustyX May 26 at 18:51

@BloodyPeasant gcc does not have an error message that says "Mismatching the argument type "char" and conversion specifier "s"." , it may be NetBeans that shows the error message instead of gcc, in which case NetBeans is wrong, and also have quite poor English grammar in its error messages. – nos May 26 at 19:33

@nos Ha, so poor grammar is the telltale sign that it's a NetBeans issue... Looking under the hood of NetBeans, it appears that you and RustyX are correct that this is just an IDE glitch. Thanks, all. – Bloody Peasant May 27 at 2:01

...所以您的问题需要更正:

Why does the compiler [NetBeans] complain about a mismatched argument type "char" and conversion specifier "s" in the following printf?

编写 NetBeans 的人是会犯错误的人,此错误消息是其中一种错误的体现,即我们通常所说的“错误”、“故障”或“软件故障”的症状。

关于c - 当 char * 被类型定义并通过结构访问时,为什么编译器会发现 char * 和 printf 的转换说明符 "s"不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44194688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com