取消引用void指针

Gop*_*opi 5 c pointers

我有以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我在解除引用之前转换void指针以避免警告

警告:解除引用'void*'指针

我是通过这样做打破任何规则还是这个代码好?

M.M*_*M.M 6

是的,此代码是合法的,不会导致未定义的行为(除非malloc返回NULL).