-3

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 *’)"

tadman
  • 208,517
  • 23
  • 234
  • 262

2 Answers2

1

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);
steph
  • 55
  • 9
  • oo is an int... what do I do now? – Diamondyguy Jacobs Feb 13 '21 at 21:08
  • @DiamondyguyJacobs: Use [`snprintf`](https://man7.org/linux/manpages/man3/snprintf.3p.html). Or [`asprintf`](https://man7.org/linux/man-pages/man3/asprintf.3.html) if you don't care about Windows, or have an implementation handy. Also, I don't think it would work with an `int oo` on C++, either. – rici Feb 13 '21 at 21:14
  • Try and link to a canonical reference, not some "tutorials" site. – tadman Feb 14 '21 at 00:38
1

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.

tadman
  • 208,517
  • 23
  • 234
  • 262