The most important problem I see is that you are assigning the text
pointer to your struct's text
pointer, which is most likely wrong since the text
field is not const
.
Removing the const
from the parameter could also be wrong, adding it to the struct
field could be Ok if you ensure that the contents pointed to by this pointer will remain valid through out the life of the struct instance.
What you are trying to do is a lot cleaner if you just memset(&widget, 0, sizeof(widget))
1 and then initialize each field like this
struct widget instance;
memset(&instance, 0, sizeof(instance));
instance.x = x;
instance.y = y;
instance.text = malloc(1 + text_size);
if (instance.text != NULL)
strcpy(instance.text, text);
instance.text_size = text_size;
instance.text_font = text_font;
and then the
widgets[widget_count++] = instance;
part, should not go in that function, that function should just
return instance;
wherever you allocated the widgets
array manipulate both the array and the widget_count
variable, don't make them global just to be able to access them from another function, if you must access them from another function pass them as parameters, if you have to modify widget_count
in another function pass it's address as a paramter.
But the way you have it, the context is not clear, so you might end up doing very bad things when the code gets more complex.
1You need to include string.h
in order to use memset()
and strcpy()