I am working on a project for school and I have managed to figure out a work around by doing something really clunky with my code. I have a structure that holds multiple fields, and I am trying to access the following field (as it is declared in the struct named current_event).
int *number_of_couples;
and later down into the program I call this value so I can dynamically allocate an array based on this *number_of_couples field. Essentially I am trying to use this as a “length” operator as C does not have (good) solution.
Before I was trying to implement the following code:
int *permutable_array;
permutable_array = malloc((current_event->number_of_couples) * sizeof(int)); //Line 91
if(permutable_array == NULL){
panic("permutable_array"); //Ensures that Malloc was successful.
}
which would in turn throw the following error:
Line 91: error: invalid operands to binary * (have ‘int *’ and ‘unsigned int’)
I have made a very sloppy work around because at this point I just want to get the program working (hour three of pure programming! rock on!). So I implemented:
int *permutable_array;
int avoid_my_bug = (int) current_event->number_of_couples;
permutable_array = malloc(avoid_my_bug * sizeof(int));
if(permutable_array == NULL){
panic("permutable_array");
}
Which works. Now I somewhat understand the error that it is telling me. I suspect it has something to do with the fact that I stored the value of number_of_couples as a pointer within current_event, which is also a pointer. So really if the value of number_of_couples is 4, the path the program makes to get to that value is:
ptr_to_current_event -> ptr_to_number_of_couples -> 4
I can use my sloppy work-around, but it is obvious that I am doing it to avoid a bug. I would rather learn why the code will not compile. I also tried doing:
permutable_array = malloc((*current_event->number_of_couples) * sizeof(int)); //Line 91
which should have dereferenced the pointer returned by current_event->number_of_couples, however it crashes. Any solutions?
*EDIT*
It is initialized by the following line of code:
fscanf(input_file, "%i", ¤t_event->number_of_couples);
and is referenced at least three times (there is a valid int value stored in it) by the program before reaching my code. Remember, the second bit works, therefore it is definitely initialized.
You shouldn’t be storing integer values inside pointers. Pointers are made to point at things, you should rarely need to convert a pointer to an integer type. If you do you should use either the
uintptr_torintptr_ttypes.You should either dereference the pointer (assuming it is pointing at a valid
int) or change the type ofnumber_of_couplesso that it is not a pointer. If you leave it as a pointer, you must ensure it is pointing to a validintobject before trying to dereference it, but based on your usage and context above, it doesn’t need to be a pointer.