14

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

For instance, typedef unsigned char int8 means you can use "int8" to declare variables of type 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]?

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?

user2410592
  • 183
  • 1
  • 3
  • 8
  • Your `int8` documents the intent - you will be storing small numbers, rather than a character. Also, typically the convention is `uint8_t` as declared in the C99 types. –  May 22 '13 at 17:52

2 Answers2

32

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

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

typedef unsigned char array[10];

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

int fct_foo(array* arr)

says fct_foo is a function that takes a pointer to an array of 10 unsigned char as an argument and returns an int.

Without the typedef, that would be written as

int fct_foo(unsigned char (*arr)[10])
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • 7
    And it means that within the function `fct_foo`, the array will have to be used with `(*arr)[i]`, for example, to get at the `i`th character in the array. – Jonathan Leffler May 22 '13 at 18:30
  • @Daniel Fischer : what would be the argument type if above function is declared as `int fct_foo(array arr)'. ? I am confused a bit here. – Shivakumar Mar 04 '16 at 12:16
  • @Shivakumar Same as if you declared it `int fct_foo(unsigned char arr[10])`, as a function argument the array type is converted to a pointer type, so effectively the function is declared `int fct_foo(unsigned char *arr)`. – Daniel Fischer Mar 04 '16 at 12:30
  • Nice though it is a bit hard to deduce `takes a pointer to an array of 10 unsigned char ` – sjsam Jul 04 '16 at 06:02
4

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

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

Community
  • 1
  • 1
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431