This code would have worked in C++, but it's giving me an error in C:
setvVec3("objs[" + oo + "].color", obj.color);
and the error:
"invalid operands to binary + (have ‘char *’ and ‘char *’)"
This code would have worked in C++, but it's giving me an error in C:
setvVec3("objs[" + oo + "].color", obj.color);
and the error:
"invalid operands to binary + (have ‘char *’ and ‘char *’)"
As @kol pointed out, you cannot concatenate strings in C with the + operator: You can however use the function strcat
. If you want to use strcat
to concatenate the three strings, your code will need to look more like this:
/* assuming oo is a char* */
char str[100] = "objs[";
setvVec3(strcat(strcat(str, oo), "].color"), obj.color);
Please note that I chose the array size at random, but keep in mind that the size of the destination character array will need to be large enough to hold the concatenated string, otherwise you will likely spill into unwanted memory.
To find more information about the C function strcat
, check out this link:
https://man7.org/linux/man-pages/man3/strcat.3.html
EDIT: Since you say that oo
is an integer, you will need to additionally convert it to a character array using the function snprintf
, like so:
/* assuming oo is a not char*, but rather an int */
char str[100] = "objs[";
char ootochar[10];
snprintf(ootochar, 10, "%d", oo);
setvVec3(strcat(strcat(str, ootochar), "].color"), obj.color);
The conventional way is to use sprintf
to use formatted buffers, like this:
int bsize = 100;
char buffer[bsize];
snprintf(buffer, bsize "objs[%s].color", obj.color);
So long as obj.color
isn't egregiously long this will work. Technically you should pay attention to the return code to ensure it was successful.
Note the use of snprintf
here, which is the safe version of sprintf
. The old sprintf
function will overflow your buffer without warning and can cause serious bugs in programs. snprintf
is the same but with that limit argument.