Bryan Fok
Bryan Fok

Reputation: 3487

Converting Char Array to Integer

I fall into a interesting problem. When I first call string_to_int, stack created a memory buffer for size 6, and converted to a correct integer. But at the second call, IMO, stack reused the buffer (because smaller than size 6?), i still see content " 513" at the break point, so atoi converted to 56513 instant of 56.

How should I do array to int properly and fast ? I can't use strtoi, or stoi because the array can be sometimes fill by space only. i can't directly pass the array to atoi because the array (char stream from network), for example, can be "123456" but it actually contain 2 separate values "123" and "456"

    static int string_to_int(const char* number, int size)
    {
        char stackbuf[size];
        memcpy(stackbuf, number, size);
        return atoi(stackbuf);
    }

char* ptr1 = "   513"

string_to_int(ptr1, 6); //result = 513

char* ptr2 = "056"

string_to_int(ptr2, 3); //result = 56513

Upvotes: 2

Views: 3687

Answers (2)

Foon
Foon

Reputation: 6433

As noted by iharob, the issue is that in your 2nd case, you don't have a null-terminated string for atoi to work with.

static int string_to_int(const char* number, int size)
    {
        char stackbuf[size+1];
        memcpy(stackbuf, number, size);
        stackbuf[size] = '\0'; //or you could use strncpy
        return atoi(stackbuf);
    }

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You need the nul terminator for atoi to work correctly, try strcpy() instead of memcpy() or copy size + 1 bytes.

Upvotes: 3

Related Questions