Reputation: 1633
If I have the following code, where does the sentence in sprintf
get stored?
Is it stored in the 100 bytes malloc
has provided or is it stored somewhere else and the store
pointer now points to the new location?
char *store = malloc(100);
int num = 77;
sprintf(store, "the number was: %d", num);
Upvotes: 3
Views: 374
Reputation: 28251
I agree with the other answers here; let me just present how you can discover the answer to similar questions by yourself.
In C, arguments to functions are passed by value. That is, a function cannot change the value of its argument. This code
sprintf(store, /* whatever */);
cannot change the value of the pointer store
, so it cannot make it point to somewhere else.
If a function has to change the value of a pointer, it has to receive a pointer-to-pointer instead. It happens that sprintf
has just such a variant, called asprintf
(because it does allocate+sprintf):
int asprintf(char **strp, const char *fmt, ...);
As you can see, its first parameter is a pointer-to-pointer, so it has the power to point the pointer to another place.
For reference, here is the declaration for sprintf
:
int sprintf ( char * str, const char * format, ... );
Upvotes: 4
Reputation: 311478
sprintf
does not allocate memory on its own - it just stores its the input on a previously allocated buffer. In your case, this is indeed the buffer you allocated with the malloc
call.
Upvotes: 5