Struct element [array versus pointer]

What is the advantage of declaring an element of structure C as in an array of size 1 instead of a pointer:

struct {
  a_struct_t a_member[1];
  ...
}b_struct;

Thanks in advance

+3
source share
5 answers

So, I think it was said that the main difference between pointers and arrays is that you need to allocate memory for pointers.

The hard part of your question is that even when you allocate space for your structure, if your structure contains a pointer, you need to allocate SECOND time for the pointer, but the pointer itself will be allocated as part of struct allocaiton.

1, - , ( ).

0

, , . , . , , / :

struct X {
    time_t birthday;
    char name[1];
};

struct X *x = malloc(sizeof(*x) + 35);
x->birthday = mktime(&t);
strcpy(x->name, "no more than 35 characters");

- , , NUL, , , , , strlen() . ( , , ).

() , , , , . , ( ) , .

+5

, , - . :

a_struct_t* a_member;

. a_struct_t. , , 1:

a_struct_t a_member[1];

a_struct_t . , :

a_struct_t a_member;

(.. *a_member a_member).

+2

" 1 "? , , quiestion . , " 1 (-)". " "? ? , ?

, 1 -,

struct { 
  a_struct_t a_member; 
} b_struct; 

, "struct hack".

struct { 
  ...
  a_struct_t a_member[1]; 
} b_struct; 

struct. , , , . , , .

P.S. "struct hack", 0, C (.. ).

+2

.

- , .

0

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


All Articles