handdy
handdy

Reputation: 1

Whether a pointer to struct can directly assign value to struct's members?

//whether this code block on my textbook is wrong? //I tried but failed to run and terminal shows segmentation fault.

typedef struct{
    _I num;
    _u32 p[];
}_BUF;
_BUF create_buf(_I size){
    void *p = malloc(size + sizeof(_BUF)));
    _BUF *pbuf;  // a pointer to _BUF 
    pbuf->p = p; // pbuf->p directly points allocated memory. 
    pbuf->num = size;
    return pbuf;
}

Upvotes: 0

Views: 40

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58528

The flexible array member p of the _BUF type is not a pointer. That array is always located immediately after the num member (with possibly a fixed amount of padding in between). It is not possible to assign to an array object; you cannot make that array refer to memory somewhere else.

The malloc(size + sizeof(_BUF)) allocates the memory for both at once. So a correct implementation of this function would simply be

typedef struct{
    _I num;
    _u32 p[];
}_BUF;

_BUF *create_buf(_I size){
    _BUF *pbuf = malloc(size + sizeof(_BUF)));
    pbuf->num = size;
    return pbuf;
}

There is no need for an intermediary void *; even though malloc returns void *, you can and should convert the return value directly to the type you actually want, and no cast is required.

And, as Craig Estey points out, returning a _BUF by value makes no sense here; it needs to be a pointer. Hopefully that was just a typo.

If the code you put in your question is really copied correctly from your textbook, then your textbook is talking nonsense, and you should probably get a better one.

Upvotes: 1

Related Questions