简体   繁体   English

C 函数中的指针需要无符号类型数组,但我的数组是有符号的

[英]pointer in C function needs unsigned type array, but my array is signed

I have a function as follows that processes the information contained in an array of type unsigned char:我有一个函数,它处理包含在 unsigned char 类型数组中的信息:

unsigned char LRCsimple(unsigned char *p, createLRC , unsigned char length)
{

}

Works great for mostly unsigned char arrays.适用于大多数无符号字符数组。

Now, I have a signed array and when I use such a function and it works very well, but I have a warning when compiling the code:现在,我有一个带符号的数组,当我使用这样的函数时,它工作得很好,但是在编译代码时出现警告:

> ../src/apptcpipserver.c:102:9: warning: pointer targets in passing argument 1 of 'LRCsimple' differ in signedness [-Wpointer-sign]
         if (0x01 == LRCsimple(apptcpipserverData.cRxedData,0x00,(apptcpipserverData.cRxedData[0x02] - 0x02)))

If I want to avoid this warning, I think the optimal solution is to create a function similar to the one above, but for a signed array, as follows:如果我想避免这个警告,我认为最佳解决方案是创建一个类似于上面的函数,但对于有符号数组,如下所示:

unsigned char signedLRCsimple(char *p, createLRC , unsigned char length)
{

}

Or is there something else I can do to avoid that warning message?或者我还能做些什么来避免该警告消息?

Strict aliasing rule allows unsigned char and char alias.严格的别名规则允许unsigned charchar别名。 Therefore you should be able reuse LRCsimple for processing char* .因此,您应该能够重用LRCsimple来处理char*

Therefore signedLRCsimple could be implemented as:因此, signedLRCsimple可以实现为:

unsigned char signedLRCsimple(char *p, createLRC xxx, unsigned char length)
{
   return LRCsimple((unsigned char*)p, xxx, length);
}

To avoid forcing client to change their code to use signedLRCsimple you could use generic selection introduced in C11 in form of _Generic .为避免强制客户端更改其代码以使用signedLRCsimple您可以使用 C11 中以_Generic形式引入的泛型选择 Typically it is used to select a function pointer basing on the type of first argument of _Generic .通常,它用于根据_Generic的第一个参数的类型选择函数指针。

#define LRCsimple(p, xxx, length)          \
  _Generic((p), unsigned char*: LRCsimple, \
                char *: signedLRCsimple)(p, xxx, length)

Whenever LRCsimple is called the generic selection selects between LRCsimple for unsigned char* and signedLRCsimple for char* .每当LRCsimple被称为之间的通用选择选择LRCsimpleunsigned char*signedLRCsimplechar* For other types an error is raised.对于其他类型,会引发错误。

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

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