Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a void pointer

Tags:

c

pointers

I have the below code:

#include <inttypes.h>
#include <stdlib.h>
struct a
{
  void *p;
};

int main(void)
{
  struct a *ptr = malloc(sizeof(struct a));
  ptr->p = malloc(sizeof(uint8_t));
  *((uint8_t *) ptr->p) = 2;
  return 0;
}

I am casting the void pointer before dereferencing to avoid the warning

warning: dereferencing ‘void *’ pointer

Am I breaking any rule by doing this or is this code good?

like image 246
Gopi Avatar asked Jul 28 '15 06:07

Gopi


1 Answers

Yes this code is legal and does not cause undefined behaviour (unless malloc returns NULL).

like image 85
M.M Avatar answered Sep 20 '22 07:09

M.M