int to string, char* itoa

2019-09-12 05:49发布

trying to get ‘sval’ to contain the string “$1” – “$500” for array indexes 0-499. in the following code, however itoa is giving me strange strings in the code below:

    #include<iostream>
    #include <stdio.h>
    #include <stdlib.h>
    using namespace std;


    typedef struct data_t {
        int ival;
        char *sval;
    } data_t;

    void f1(data_t **d);
    int main()
    {
    data_t *d;

        d=static_cast<data_t*>(malloc(500));  //is this even needed?
        d = new data_t[500];
        f1(&d);
    }

    /* code for function f1 to fill in array begins */
    void f1(data_t **d)
    {
        int i;
        char str[5];
        for (int i=0; i<500; i++)
        {
            (*d)[i].ival=i+1;
            itoa (i,str,10);
            (*d)[i].sval= str;
        }
    }

it also seems itoa has been depreciated, but that was what i got when i googled int to string

1条回答
仙女界的扛把子
2楼-- · 2019-09-12 06:30

You don't need ltoa, cout should be just fine. Why do you need to keep the number and its string representation in the array? when you do cout << 10 you get "10" on the output, you don't need any conversions of your own

You, on the other hand, do ltoa without allocating any memory for the strings, which is not healthy as you have probably noticed. You use a local variable (the same, for all the 500 array members), which you try to access after you exit the function - a big no-no, its undefined behavior.

And:

    d=static_cast<data_t*>(malloc(500));  //is this even needed?
    d = new data_t[500];

No. Not only not needed - shouldn't be there at all! When in C++ - use new and delete, never malloc, that's a C function.

查看更多
登录 后发表回答