简体   繁体   English

使用strncat进行字符串连接会导致签名错误

[英]string concatenation with strncat leads to error in signedness

update: the point of whether char, signed char, or unsigned was ultimately moot here. 更新:在这里最终讨论的是char,signed char还是unsigned的问题。 it was more appropriate to use memcpy in this situation, since it works indiscriminately on bytes. 在这种情况下使用memcpy更合适,因为它可以不加区分地在字节上工作。

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. 在下面的代码,我试图填补bufferdatabuffer的,编译器警告我在符号性的差别。

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;    
 }
}

显然,在您的编译器中char是带signed char ,因此是警告消息。

char * strncat ( char * destination, char * source, size_t num );

so as your destination buffer is unsigned char so there will be a warning of sign. 因此,由于您的目标缓冲区是unsigned char,因此会出现符号警告。 You can either change your buffer to char array if signed is not necessary else you can ignore warnings using -w option in compiler. 您可以在不需要签名的情况下将缓冲区更改为char数组,否则可以在编译器中使用-w选项忽略警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM