使用 strncat 进行字符串连接会导致符号错误
更新:关于 char、signed char 还是 unsigned 的问题最终没有意义。在这种情况下使用 memcpy 更合适,因为它在字节上不加区别地工作。
不可能是一个更简单的操作,但我似乎错过了一个关键步骤。在下面的代码中,我尝试用 buffer
填充 bufferdata
,编译器会警告我符号性存在差异。
unsigned char buffer[4096] = {0};
char *bufferdata;
bufferdata = (char*)malloc(4096 * sizeof(bufferdata));
if (! bufferdata)
return false;
while( ... )
{
// nextBlock( voidp _buffer, unsigned _length );
read=nextBlock( buffer, 4096);
if( read > 0 )
{
bufferdata = strncat(bufferdata, buffer, read); // (help)
// leads to: pointer targets in passing argument 2 of strncat differ in signedness.
if(read == 4096) {
// let's go for another chunk
bufferdata = (char*)realloc(bufferdata, ( strlen(bufferdata) + (4096 * sizeof(bufferdata)) ) );
if (! bufferdata) {
printf("failed to realloc\n");
return false;
}
}
}
else if( read<0 )
{
printf("error.\n");
break;
}
else {
printf("done.\n");
break;
}
}
update: the point of whether char, signed char, or unsigned was ultimately moot here. it was more appropriate to use memcpy in this situation, since it works indiscriminately on bytes.
Couldn't be a simpler operation, but I seem to be missing a critical step. In the following code, I am attempting to fill bufferdata
with buffer
for which the compiler warns me of a difference in signedness.
unsigned char buffer[4096] = {0};
char *bufferdata;
bufferdata = (char*)malloc(4096 * sizeof(bufferdata));
if (! bufferdata)
return false;
while( ... )
{
// nextBlock( voidp _buffer, unsigned _length );
read=nextBlock( buffer, 4096);
if( read > 0 )
{
bufferdata = strncat(bufferdata, buffer, read); // (help)
// leads to: pointer targets in passing argument 2 of strncat differ in signedness.
if(read == 4096) {
// let's go for another chunk
bufferdata = (char*)realloc(bufferdata, ( strlen(bufferdata) + (4096 * sizeof(bufferdata)) ) );
if (! bufferdata) {
printf("failed to realloc\n");
return false;
}
}
}
else if( read<0 )
{
printf("error.\n");
break;
}
else {
printf("done.\n");
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然,在您的编译器中,
char
是signed char
,因此出现警告消息。Obviously in your compiler
char
issigned char
, thus the warning message.因此,由于您的目标缓冲区是无符号字符,因此会出现符号警告。如果不需要签名,您可以将缓冲区更改为 char 数组,否则您可以在编译器中使用 -w 选项忽略警告。
so as your destination buffer is unsigned char so there will be a warning of sign. You can either change your buffer to char array if signed is not necessary else you can ignore warnings using -w option in compiler.