also it occupies less space then an array.
It doesn't, since you will have to point to some data anyway. Assuming you point to a buffer of the same size, you end up with sizeof(void *) + sizeof(char [10])
in total.
Also, in both cases I can initialize:
struct my_struct p { .p = 10, .s = "abcd" };
Yes, because the compiler is setting up the literal string in memory and pointing the s
member to it. In this case, you are using sizeof(void *) + sizeof(char [5])
bytes in total.
I can't easily use strncpy() on char *, it has to be valid pointer on the allocated memory.
No, you can use strncpy()
in both cases.
Regarding what you should use: the choice is not so much about advantages and disadvantages. Instead, you should use whatever you need. For instance, if you don't know in advance the maximum size of the array, you have no choice but to go for the pointer approach. If you do know, then you can use both approaches; but the array one will be simpler to maintain.
Performance considerations can also influence your decisions. For instance, assuming you operate on many instances of the struct
, it depends on how you are accessing the struct
and the kind of data structure you are using to hold the instances, i.e. the access patterns to the data. Many times an embedded array is faster, but not always.