简体   繁体   中英

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

您需要使用nul终止符才能使atoi正常工作,请尝试使用strcpy()而不是memcpy()或复制size + 1个字节。

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM