How can i interpret this : sprintf(var_ptr_char+strlen(var_ptr_char).... C code

134 views Asked by At

how could i interpret this : var_ptr_char+strlen(var_ptr_char) in the follow piece of C code :

#define INT_CONSTANT 80
char var_ptr_char[1024];
strcat(var_ptr_char,"SOMETHING");
sprintf(var_ptr_char+strlen(var_ptr_char),":%d",INT_CONSTANT);

and how much size will I put in order to change sprintf by snprintf.

Thanks!

1

There are 1 answers

2
Carles Araguz On BEST ANSWER

The first argument of sprintf is a char pointer (i.e a char buffer.) The function will "print" at that buffer and will start at the position pointed to by the pointer.

Adding N to a pointer, means pointing to the N-th position. Therefore, if we add strlen(var_ptr_char) to var_ptr_char, we're effectively passing the pointer to the last character of the buffer (assuming it did already contain a valid string).

The snprintf call, could then be like this:

snprintf(var_ptr_char + strlen(var_ptr_char), 1024 - strlen(var_ptr_char) - 1, ":%d", INT_CONSTANT);

TL;DR: It appends the string to the end of the already stored string in var_ptr_char.