K. Fenster K. Fenster - 12 days ago 5
C++ Question

Trouble Understanding sprintf with 'char * str + int'

I was looking at a project and came across the following code and am unable to figure out what the sprintf is doing in this context and was hoping someone might be able to help me figure it out.

char storage[64];
int loc = 0;
int size = 35;

sprintf(storage+(loc),"A"); //Don't know what this does
loc+=1;
sprintf(storage+(loc),"%i", size); //Don't know what this does
loc+=4;
sprintf(storage+(loc), "%i", start); //Don't know what this does

start += size;
loc += 3;


The code later does the following in another part

string value;
int actVal;
int index = 0;
for(int j = index+1; j < index+4; j++)
{
value += storage[j];
}
istringstream iss;
iss.str(value);
iss >> actVal; //Don't understand how this now contains size


The examples I have seen online regarding sprintf never covered that the above code was possible, but the program executes fine. I just can't figure out how the "+loc" affects storage in this instance and how the values would be saved/stored. Any help would be appreciated.

Answer

Ugly code! Regardless, for the first part, storage+(loc) == &storage[loc]. You end up with a string "A35\0<unknown_value>1234\0", assuming start = 1234, or in long form:

sprintf(&storage[0],"A");
sprintf(&storage[1],"%i", size);
sprintf(&storage[5], "%i", start);

For the second part, assuming we have the "A35\0<unknown_value>1234\0" above, we get:

 value += '3';
 value += '5';
 value += '\0';
 value += '<unknown_value>'; // This might technically be undefined behaviour

So now value = "35".

iss.str(value);
iss >> actVal;

This turns the string into an input stream and reads out the first string representing an integer, "35", and converts it into an integer, giving us basically actVal = atoi(value.c_str());.

Comments