gpt4 book ai didi

c - 警告 : pointer targets in passing argument 2 of ‘strcat’ differ in signedness

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:24 25 4
gpt4 key购买 nike

下面是简单的代码:

unsigned char buf[255];
unsigned char msg[255];

while((res = read (fd, buf, (sizeof buf)-1)) > 0)
{
buf[res] = '\0';
strcat(msg, buf);
length += res;
if(length >= 10)
break;
}

这一行 strcat(msg, buf); 给出以下警告:

warning: pointer targets in passing argument 1 of ‘strcat’ differ in signedness

我已经尝试了为类似问题找到的所有解决方案,但没有太大帮助。当两个变量具有相同的符号时,任何人都可以帮助为什么这会出错。我怎样才能删除它。谢谢

编辑:

unsigned const char *buf[255];
unsigned char *msg[255];
strcat(msg, buf);

现在它发出警告:

warning: passing argument 2 of ‘strcat’ from incompatible pointer type

最佳答案

扩展我的 comment变成类似于答案的东西。

strcat()函数需要普通的 char *:

char *strcpy(char * restrict s1, const char * restrict s2);

您正在通过 unsigned char * .这些是不同的类型(即使普通 char 是无符号类型)。 str*()函数的设计目的不是采用 unsigned char 的数组.要“安抚”(或“强制”)编译器接受调用,您需要转换指针:

strcat((char *)msg, (char *)buf);

或者编写并使用一系列自动执行此操作的函数:

static inline unsigned char *ustrcat(unsigned char *dst, const unsigned char *src)
{
return (unsigned char *)strcat((char *)dst, (char *)src);
}

如果您需要经常使用这些功能,这可能是个好主意;这意味着您不必在代码周围留下太多难看的转换。您可以添加 restrict如果您愿意,可以使用限定词。


注意三种类型 char , unsigned charsigned char是不同的,即使是普通的 char与其他两个中的一个具有相同的值范围。 ISO/IEC 9899:2011 §6.2.5 类型 说:

¶15 The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.45)

45) CHAR_MIN, defined in <limits.h>, will have one of the values 0 or SCHAR_MIN, and this can be used to distinguish the two options. Irrespective of the choice made, char is a separate type from the other two and is not compatible with either.


您的代码容易受到缓冲区溢出的影响,因为您没有在任何地方检查长度。这与您收到的编译警告无关,但您应该确保没有将太多数据复制到目标缓冲区。


你也试过:

unsigned const char *buf[255];
unsigned char *msg[255];
strcat(msg, buf);

现在您将指针传递给一个函数,该函数只需要指向 char 的指针— 编译器有权提示。

关于c - 警告 : pointer targets in passing argument 2 of ‘strcat’ differ in signedness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43992991/

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