How to read this declaration or C array initialization?

char *names[] = {
        [3] = "foo", 
        [1] = "bar", 
        [0] = "man"};

int i;
for (i=0; i<sizeof(names)/sizeof(char); i++)
{
    puts(names[i]);
}

What is the function of parentheses in the above declaration? In addition, why the resulting cycle is repeated 3 times instead of 4 and produces this conclusion:

person

bar

+3
source share
3 answers

The number in parentheses is the indexes of the initializers. This is the function of C99.

Given that your sample code does exploit this flaw, the reason you get the output you make is because "foo" is stored in names[3], and NULLstored in names[2]. Your program crashes on an attempt puts(names[2])that matches the puts(NULL).

16 32 - sizeof(char) , sizeof(char *).

:

#define DIMENSION_OF (a) (sizeof(a)/sizeof(a[0]))

- C99 , " ".

, , , , , . , C99 .

, C99 . , C99 ++, ANSI C, ++. C99 ANSI C . C99, . " ". C. C99 .

, " " C99, . for-init- , ANSI-C, . complex , ANSI-C, .

+3

, , :

static int number[3] = { [0] = 5, [2] = 7 };

: [0] 5; [1] 0; [2] 7.

, for, .

+4

( ) char, , ; "" ; man 0, foo 3... , .

sizeof(char *), . ; 3, 0 2, (2 < 3, 3 < 3 - false), C 0.

+2

Source: https://habr.com/ru/post/1758543/


All Articles