I'm working on some legacy C code (normally I work in C#) and I'm having a hard time with one specific string behavior.
The code we have looks something like this:
int no = 0;
const char *values[1000];
for(int i = 0; i < num_of_values; i++) {
if (/*is invalid*/) continue;
values[no++] = list_of_objs[i]->value;
}
send_to_display(values, no);
where list_of_objs[i]->value
is a const char *
and list_of_objs
itself is declared as cpp_extern const struct obj_info list_of_objs[]
and populated with static data. I believe these are string literals, at this point, and they're used elsewhere in the code as-is, so I can't modify their inital values.
I'm tasked with adding a dynamic prefix to each entry in the values
array based on another value. (For the sake of simplicity in the code below, I'm just showing one value - I can easily if
or ?:
to handle the multiple cases.) In C#, this would be trivial with string concatenation, but I know C's relationship with strings is much more... complex.
My naïve attempt was to declare a single buffer, sprintf
into it, and then add that to the values
array, but that gave me a list of the final value, repeated i
times. (I understand why: reusing the buffer meant that every element in the array was pointed at the same buffer)
int no = 0;
const char *values[1000];
char buf[MAX_STRING_LENGTH];
for(int i = 0; i < num_of_values; i++) {
if (/*is invalid*/) continue;
sprintf(buf, "Value: %s", list_of_objs[i]->value);
values[no++] = buf;
}
send_to_display(values, no);
I've also tried to sprintf
directly into the values
array, but that gives me a warning-that-should-be-an-error (the const
qualifier is discarded).
sprintf(values[no++], "Value: %s", list_of_objs[i]->value);
I know I could declare a buffer in each iteration of the loop and use that, but I worry that that's going to leak memory.
How can I safely get my modified string into this array?