how to set pointer to a memory to NULL using memset?

后端 未结 9 864
执笔经年
执笔经年 2020-12-11 08:35

I have a structure

typedef struct my_s {

   int x;
   ...
} my_T;

my_t * p_my_t;

I want to set the address of p_my_t to

9条回答
  •  执念已碎
    2020-12-11 09:24

    What exactly are you trying to do? p_my_t is already a pointer, but you haven't allocated memory for it. If you want to set the pointer to NULL, simply do

    p_my_t = NULL;
    

    Trying to dereference this pointer will result in a segmentation fault (or access violation on Windows).

    Once the pointer actually pointers to something (e.g. via malloc() or by assigning to it the address of a struct my_T), then you can properly memset() it:

    memset(p_my_t, 0, sizeof(struct my_T));
    

    This will zero out the entire structure, setting all fields to zero.

提交回复
热议问题