typedef 定长数组 [英] typedef fixed length array
问题描述
我必须定义一个 24 位数据类型.我使用 char[3]
来表示类型.我可以将 char[3]
定义为 type24
吗?我在代码示例中尝试过.我把 typedef char[3] type24;
放在我的头文件中.编译器没有抱怨它.但是当我在我的 C 文件中定义一个函数 void foo(type24 val) {}
时,它确实抱怨.我希望能够定义像 type24_to_int32(type24 val)
而不是 type24_to_int32(char value[3])
之类的函数.
I have to define a 24-bit data type.I am using char[3]
to represent the type. Can I typedef char[3]
to type24
? I tried it in a code sample. I put typedef char[3] type24;
in my header file. The compiler did not complain about it. But when I defined a function void foo(type24 val) {}
in my C file, it did complain. I would like to be able to define functions like type24_to_int32(type24 val)
instead of type24_to_int32(char value[3])
.
推荐答案
typedef 为
typedef char type24[3];
然而,这可能是一个非常糟糕的主意,因为结果类型是一个数组类型,但它的用户不会看到它是一个数组类型.如果用作函数参数,它将按引用传递,而不是按值传递,然后它的 sizeof
将是错误的.
However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof
for it will then be wrong.
更好的解决方案是
typedef struct type24 { char x[3]; } type24;
您可能还想使用 unsigned char
而不是 char
,因为后者具有实现定义的签名.
You probably also want to be using unsigned char
instead of char
, since the latter has implementation-defined signedness.
这篇关于typedef 定长数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!