int main()
{
int n = 56;
char buf[10]; //want char* buf instead
sprintf(buf, "%i", n);
printf("%s\n", buf);
return 0;
}
This piece of code works, my question is what if i want the same behaviour, with buf being a char* ?
int main()
{
int n = 56;
char buf[10]; //want char* buf instead
sprintf(buf, "%i", n);
printf("%s\n", buf);
return 0;
}
This piece of code works, my question is what if i want the same behaviour, with buf being a char* ?
The main difference when writing
char* buf;
is that it is uninitialized and no memory is allocated, so you'll have to take care yourself:
char* buf = malloc(10 * sizeof(char));
// ... more code here
free(buf); // don't forget this or you'll get a memory leak
This is called dynamic memory allocation (as opposed to static allocation) and it allows you nice things like changing the amount of allocated memory at runtime using realloc
or using a variable in the malloc
call.
Also note that memory allocation can fail if the amount of memory is too large, in this case the returned pointer will be NULL
.
Technically, sizeof(char)
above isn't needed because 1 char
will always be 1 byte in size, but most other data types are bigger and the multiplication is important - malloc(100)
allocates 100 bytes, malloc(100 * sizeof(int))
allocates the amount of memory needed for 100 int
s which usually is 400 bytes on 32-bit systems, but can vary.
int amount = calculate_my_memory_needs_function();
int* buf = malloc(amount * sizeof(int));
if (buf == NULL) {
// oops!
}
// ...
if (more_memory_needed_suddenly) {
amount *= 2; // we just double it
buf = realloc(buf, amount * sizeof(int));
if (!buf) { // Another way to check for NULL
// oops again!
}
}
// ...
free(buf);
Another useful function is calloc
that takes two parameters (first: number of elements to allocate, second: size of an element in bytes) and initializes the memory to 0.
buf
is an array statically allocated on the stack. For it to be of type char *
you need to allocate dynamically the memory. I guess what you want is something like this:
int main()
{
int n = 56;
char * buf = NULL;
buf = malloc(10 * sizeof(char));
sprintf(buf, "%i", n);
printf("%s\n", buf);
// don't forget to free the allocated memory
free(buf);
return 0;
}
EDIT: As pointed out by 'Thomas Padron-McCarthy' in the comments, you should not cast the return of malloc()
. You will find more info here. You could also remove completely the sizeof(char)
as it will always by 1
.