Reputation: 18895
I am trying to use malloc to allocate heap memory for an array of struct pointers, but I cannot get it to work. Below is my code, but when I compile with gcc, I got errors like this "error: invalid type argument of ‘->’ "
The array I want to set up an array of mystruct_pointer, which should point to the actual __mystruct_t, and I think I can use "->" on its member field. Where is wrong with my code? I think it should work. thanks
typedef struct
{
int id;
bool status;
} __mystruct_t;
typedef __mystruct_t* mystruct_pointer;
mystruct_pointer struct_ptr_array;
void my_init(int number)
{
struct_ptr_array = (mystruct_pointer) malloc(sizeof(__mystruct_t) * number);
int i;
for (i = 0; i < number; i++) /* initialize the array of struct pointers */
{
struct_ptr_array[i]->id = i;
struct_ptr_array[i]->status = false;
}
}
Upvotes: 0
Views: 276
Reputation: 91
Replace two lines by
struct_ptr_array[i].id = i;
struct_ptr_array[i].status = false;
Upvotes: 1
Reputation: 215330
Problems like these come from doing obscure things. You typedef-hide a pointer and instantly you have made the program unreadable to yourself. And that's the only thing the typedef achieved. So never hide pointers with typedefs, it is very bad practice.
Other issues:
Avoid double underscore because that's reserved for compiler identifiers.
Don't cast the result of malloc, because doing so is completely pointless in C and also potentially dangerous on old C compilers.
Handle the case where malloc fails because there's no heap space available.
Never use variables with global scope, it is very bad practice that leads to spaghetti code. And there is never a reason to do so in C.
The code should be fixed as follows:
typedef struct
{
int id;
bool status;
} mystruct_t;
static mystruct_t* struct_ptr_array;
void my_init(int number)
{
struct_ptr_array = malloc(sizeof(mystruct_t) * number);
if(struct_ptr_array == NULL)
{
handle_error();
return ;
}
for (int i = 0; i < number; i++) /* initialize the array of struct pointers */
{
struct_ptr_array[i].id = i;
struct_ptr_array[i].status = false;
}
}
Upvotes: 2
Reputation: 659
Replace '->' by '.'. Since 'struct_ptr_array[i]' already dereference the pointer.
Upvotes: 4
Reputation:
struct_ptr_array
is a pointer, but you index it, so you get an actual __mystruct_t
, not the pointer. Thus, simply use:
struct_ptr_array[i].id = i;
struct_ptr_array[i].status = false;
Upvotes: 1