Drukenme Drukenme - 24 days ago 11
C Question

What's the difference between char[] & char* when declare inside struct?

I'm trying to look into a piece of code, and something confused me.

When we use structure below:

struct sdshdr {
int len;
int free;
char buf[];
};


We will allocate memory like this:

struct sdshdr *sh;
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);


So, what's the difference between
char[]
&
char*
when buff has been declared inside struct?

Is
char[]
means continues address?

Answer
struct sdshdr {
        int len;
        int free;
        char buf[];
    };


struct shshdr *p = malloc(sizeof(struct shshdr));

       +---------+----------+-----------------+ 
p -->  | int len | int free | char[] buf 0..n |  can be expanded 
       +---------+----------+-----------------+ 

struct sdshdr {
        int len;
        int free;
        char *buf;
    };

struct shshdr *p = malloc(sizeof(struct shshdr));

       +---------+----------+-----------+ 
p -->  | int len | int free | char* buf | cannot be expanded, fixed size
       +---------+----------+-----------+ 
                                   |
                            +-----------+
                            |           | 
                            +-----------+

in the first case this is valid:

struct shshdr *p = malloc(sizeof(struct shshdr)+100); // buf is now 100 bytes
...
struct shshdr *q = malloc(sizeof(struct shshdr)+100);

memcpy( q, p, sizeof(struct shshdr) + 100 );