Convert double to char* in C

Viewed 706

How can I convert double to char*.

#include <stdio.h>

int main() {
    char * buf;
    double number = 3.123;
    sprintf(buf,"%f",number);
    printf("%s",buf);
    return 0;
}

This method is does not want to work and I cannot know why.

2 Answers

char* buf declares buf as a character pointer, but does not actually allocate any memory for it. You should declare buf as an array to allocate memory:

char buf[128];
double number = 3.123;
sprintf(buf, "%f", number);

What you probably want is a floating-point to string conversion. What you need is not a char*, but rather an array. The difference is that an array allocates some space for the string, while a pointer is supposed to point to an already existing string, but there is no such string in your code.

Because of this, your code is producing Undefined Behavior (or UB for short), because sprintf() is attempting to write at the address that the buf pointer references. The pointer was not assigned to point to anything, so it is an uninitialized (wild) pointer. This pointer probably contains a random non-sense value and sprintf() is trying to write to it - it won't work, or even worse, will appear to work until you find a problem in a totally different part of the code.

Here is how you should do it:

#include <stdio.h>

int main(void)
{
    char buf[100];
    double number = 3.123;
    sprintf(buf, "%f", number);
    printf("%s", buf);
}

First we declare a character array. It can be any length, but for simplicity I chose 100. We can then use this array in a similar way, by writing to it using sprintf().

Now, there may be another problem. It won't show up in this small piece of code, but if you use sprintf() a lot you will notice a lot of bugs if you don't pay attention to the length of the array. The array has only 100 characters, but sprintf() doesn't know that! The function will simply attempt to write past the end of the array, a bug which is called a buffer overflow, yet another case of UB, and also a very common exploit for malicious attacks.

To ease the programmer's life, C has another function that is safer, snprintf(), which works pretty much the same but takes an extra parameter, the maximum length of the array. Here is how it works:

#include <stdio.h>

int main(void)
{
    char buf[100];
    double number = 3.123;
    snprintf(buf, 100, "%f", number);
    printf("%s", buf);
}

Even if we tried to write more than 100 characters to the buffer, the function would only write 100 (actually, 99 and a null terminator), and will discard the rest of the contents. This means that, if you pass the correct value for the length of the array, a buffer overflow won't occur.

Related