int to string, char* itoa

巧了我就是萌 提交于 2020-01-06 07:55:22

问题


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:


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.



来源:https://stackoverflow.com/questions/10083830/int-to-string-char-itoa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!