Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C dereference an integer pointer in a structure

Tags:

c

I am having a problem correctly dereferencing a pointer to an integer that resides in an array of structures. The relevant parts of the code are:

typedef struct hf_register_info {
  int                   *p_id;  /**< written to by register() function */
  header_field_info     hfinfo; /**< the field info to be registered */
} hf_register_info;
.
.
hf_register_info hf[MAX_HF_COUNT];
.
.
*(hf[i].p_id) = -1;

The final line of code above causes an exception. How do I correctly deference p_id?

Thanks and regards...Paul

like image 399
Paul Offord Avatar asked Jul 21 '26 09:07

Paul Offord


1 Answers

You need to initialize your pointers. You pointers in your structs aren't pointing to anything at the moment you initialize your array.

So for every struct in your array you want to dereference your pointer and assign a value to, you'll need to allocate space in your memory first.

hf_register_info hf[MAX_HF_COUNT];

// some code here

hf[i].p_id = malloc(sizeof(int)); // or unsigned long or whatever
*(hf[i].p_id) = -1;
like image 62
CRoemheld Avatar answered Jul 23 '26 23:07

CRoemheld