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

发布于 2024-09-07 23:21:44 字数 997 浏览 6 评论 0原文

更新:关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

宁愿没拥抱 2024-09-14 23:21:44

显然,在您的编译器中,charsigned char,因此出现警告消息。

Obviously in your compiler char is signed char, thus the warning message.

自控 2024-09-14 23:21:44
char * strncat ( char * destination, char * source, size_t num );

因此,由于您的目标缓冲区是无符号字符,因此会出现符号警告。如果不需要签名,您可以将缓冲区更改为 char 数组,否则您可以在编译器中使用 -w 选项忽略警告。

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. You can either change your buffer to char array if signed is not necessary else you can ignore warnings using -w option in compiler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文