简体   繁体   中英

Confusion about array declaration

What does this mean in C:

char strings[USHRT_MAX][50];

Is it creating a jagged array of characters called strings?

No, the above does not create a jagged array of strings. It creates an array of characters with two dimensions, capable of storing up to USHRT_MAX C strings of up to 49 characters in length (the fiftieth char is used for the '\\0' terminator).

A jagged array declaration would look like this:

char *strings[USHRT_MAX];

With an array of pointers you would need to allocate memory for the individual strings, but the strings could differ in length from one element to the other. Your array, on the other hand, has all memory allocated, but it places a limit on the length of strings, and has a potential of using more memory than you need to store shorter strings.

This:

char strings[USHRT_MAX][50];

Just provides a 2 dimensional array of characters. The size is USHRT_MAX by 50. This is not a jagged array, a jagged array is one which has various length rows, conceptually this would be:

strings[0] = ['a']['\0']
strings[1] = ['j']['a']['g']['\0']
strings[2] = ['a']['r']['r']['a']['y']['\0']

Where as yours is more like:

strings[0] = ['a']['\0'][ ][ ][ ][ ]
strings[1] = ['j']['a']['g']['\0'][ ][ ]
strings[2] = ['a']['r']['r']['a']['y']['\0']

Note in the second example they all have the same number of elements in each row, but not all elements are filled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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