Question

I'm developing under a small C API and I need to create an array of structs, each with different titles. From my background in PHP I wrote the following code excerpt:

char *title = "";
for(int w = 0; w < total_workouts; w++) {
    snprintf(title, 10, "Workout %c", workouts[w].letter);
    workout_menu[w] = (SimpleMenuItem) { .title = title };
}

However, the title variable is sent as a pointer to the SimpleMenuItem object, and thus all the menu entries get the same title. I spent some time fiddling with arrays of strings and etc and could't make it work.

How would I fix the snippet of code to have different string pointers for each menu entry (each passage inside the for)?

Was it helpful?

Solution

Create some space for title dynamically INSIDE The loop

workout_menu[w].title = (char *)malloc(sizeof(char) * 10);

And then use sprintf/snprintf to copy directly into the title member of SimpleMenuItem (not a local variable)

sprintf(workout_menu[w].title, "Workout %c", workouts[w].letter)

Remember to use free() when you're finished so you don't have a memory leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top