C array initialization

Why

static char *opcode_str[] = { "DATA" , "DATA_REQUEST_ACK" , "ACK_TIMER_EXPIRED" , "ACK_UNEXPECTED_SEQ" , "ACK_AS_REQUESTED" } ; 

works but

 static char **opcode_str = { "DATA" , "DATA_REQUEST_ACK" , "ACK_TIMER_EXPIRED" , "ACK_UNEXPECTED_SEQ" , "ACK_AS_REQUESTED" } ; 

doesn't work with SEGV when opcode_str [0] is printf'd?

I think because the second listing did not allocate memory for the five elements of the pointer array, but I need a more complete explanation.

All the best

Chris.

+4
source share
1 answer

It is right. You are essentially trying to assign an array to a pointer. GCC 4.4.1 warns about this by default:

 opcode_str.c:4: warning: initialization from incompatible pointer type opcode_str.c:5: warning: excess elements in scalar initializer 

It repeats the warning about redundant elements 4 times, since you essentially put 5 pointers where only one will match. You can use gcc -Werror to make all warnings be errors.

You can do:

 static char **opcode_str = malloc(sizeof(char *) * 5); opcode_str[0] = "DATA"; opcode_str[1] = "DATA_REQUEST_ACK"; opcode_str[2] = "ACK_TIMER_EXPIRED"; opcode_str[3] = "ACK_UNEXPECTED_SEQ"; opcode_str[4] = "ACK_AS_REQUESTED"; 

But you have already found a better way to do this. As for the error, when you invoke undefined behavior, you really cannot count on a specific time to identify problems.

But I think opcode_str contains a pointer to DATA. Thus (suppose 32-bit), he will try to interpret the first four bytes in opcode_str ('D', 'A', 'T', 'A') as four char * bytes.

+10
source

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


All Articles