C语言 对数组使用 typedef 来声明新类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16698256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:26:24  来源:igfitidea点击:

Using typedef for an array to declare a new type

c

提问by user2410592

I know how to use typedef in order to define a new type (label).

我知道如何使用 typedef 来定义新类型(标签)。

For instance, typedef unsigned char int8means you can use "int8" to declare variables of type unsigned char.

例如,typedef unsigned char int8意味着您可以使用“int8”来声明 unsigned char 类型的变量。

However, I can't understand the meaning of the following statment:

但是,我无法理解以下语句的含义:

typedef unsigned char array[10]

Does that mean array is of type unsigned char[10]?

这是否意味着数组是 unsigned char[10] 类型?

In other part of code, this type was used as a function argument:

在代码的其他部分,这种类型被用作函数参数:

int fct_foo(array* arr)

Is there anyone who is familiar with this statement?

有没有人熟悉这个声明?

回答by Daniel Fischer

Does that mean array is of type unsigned char[10]?

这是否意味着数组是类型unsigned char[10]

Replace "of"with "another name for the"and you have a 100% correct statement. A typedefintroduces a new name for a type.

替换“的”“的另一个名字为”和你有一个100%正确的说法。Atypedef为类型引入了一个新名称。

typedef unsigned char array[10];

declares arrayas another name for the type unsigned char[10], array of 10 unsigned char.

声明array为该类型的另一个名称unsigned char[10],数组为 10 unsigned char

int fct_foo(array* arr)

says fct_foois a function that takes a pointer to an array of 10 unsigned charas an argument and returns an int.

sayfct_foo是一个函数,它将一个指向 10 的数组的指针unsigned char作为参数并返回一个int.

Without the typedef, that would be written as

如果没有typedef,那将被写成

int fct_foo(unsigned char (*arr)[10])

回答by Scott Chamberlain

What that does is it makes a datatype called arraythat is a fixed length array of 10 unsigned charobjects in size.

它的作用是创建一个称为array10 个unsigned char对象的固定长度数组的数据类型。

Here is a similar SO questionthat was asking how to do a fixed length array and that typedef format is explained in more depth.

这是一个类似的 SO 问题,它询问如何做一个固定长度的数组,并且更深入地解释了 typedef 格式。