Sorin
Sorin

Reputation: 910

Weird output when converting int to char*

I have an int and I want to obtain a char* containing that int. My code is:

int getLength(int x) {
    int l = 0;
    while(x) {
        l++;
        x /= 10;
    }
    return l;
}

char* toString(int x) {
    int l = getLength(x);
    char *str = new char[l];
    l--; // the digits will be placed on positions 0 to l-1
    while(l >= 0) {
        str[l] = x % 10 + '0';
        x /= 10;
        l--;
    }
    return str;
}

Some of the results:

toString(1009) = 1009Ä
toString(23) = 23L

Why? I allocated space only for l characters. (l = length of int)

Upvotes: 1

Views: 1160

Answers (4)

Brian Campbell
Brian Campbell

Reputation: 333146

You need to null terminate your string. C strings are a series of characters followed by a '\0', or null character; that's how the various string handling functions know when the string ends. Without the null, the C standard string handling functions will just keep on reading past the end of the string to whatever values happen to lie beyond it.

Remember to allocate one extra character so you have room for the null, and store a '\0' at the end:

char *str = new char[l+1];
str[l] = '\0';

By the way, new is a C++ operator. In C, you would use malloc(). In C++, it's probably better to use std::string, as it handles allocating memory and doesn't need null termination.

Upvotes: 10

Frerich Raabe
Frerich Raabe

Reputation: 94459

This doesn't answer your question (why you get that funny output, which is due to a missing null-terminator as the other answers correctly point out) directly, but since your question is tagged C++: in C++, you wouldn't even need to write the function yourself, you might be just fine with std::ostringstream:

#include <sstream>
#include <string>

std::string toString(int x)
{
    std::ostringstream stream;
    stream << x;
    return stream.str();
}

Upvotes: 1

Ahmed_Mohsen
Ahmed_Mohsen

Reputation: 295

You can get the length of the int using log10, then you need to put a null in the end of the char array

int getLength(int x) {
        return ceil(log10(x));
    }
    char* toString(int x) {
        int l = getLength(x);
        char *str = new char[l+1]; //+1 for null character
        str[l]='\0'; // putting null character at the end of char[]

        while(l >= 0) {
            str[--l] = x % 10 + '0'; // put the last digit in l - 1
            x /= 10;
        }
}

Upvotes: 0

Umer Farooq
Umer Farooq

Reputation: 7486

Put a null character at the end of the char[]. The artifcates you are seeing at the end of the char[] are garbage value.

char* toString(int x) {
    int l = getLength(x);
    char *str = new char[l+1]; //+1 for null character

    str[l]='\0'; // putting null character at the end of char[]

    l--; 
    while(l >= 0) {
        str[l] = x % 10 + '0';
        x /= 10;
        l--;
    }
    return str;
}

Upvotes: 4

Related Questions