int to string,char * itoa

时间:2012-04-10 06:01:17

标签: c++ string char int

尝试让'sval'包含字符串“$ 1” - 数组索引0-499的“$ 500”。在下面的代码中,但是itoa在下面的代码中给了我奇怪的字符串:

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

似乎itoa已被折旧,但这是我在使用google搜索字符串时得到的

1 个答案:

答案 0 :(得分:3)

您不需要ltoacout应该没问题。为什么需要在数组中保留数字及其字符串表示?当你cout << 10输出时得到“10”时,你不需要任何你自己的转换

另一方面,你没有为字符串分配任何内存ltoa,这可能并不健康,你可能已经注意到了。你使用一个局部变量(相同的,对于所有500个数组成员),你在退出函数后尝试访问它 - 一个很大的禁忌,它的未定义行为。

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

没有。不仅不需要 - 不应该在那里!在C ++中 - 使用newdelete,而不是malloc,这是一个C函数。

相关问题