int to string,char * itoa [英] int to string, char* itoa

查看:142
本文介绍了int to string,char * itoa的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试为数组索引0-499获取sval包含字符串$ 1 - $ 500。在下面的代码中,但itoa给我在下面的代码奇怪的字符串:

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

itoa似乎itoa已贬值

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

推荐答案

你不需要 ltoa cout 应该很好。为什么需要在数组中保留数字及其字符串表示形式?当你做 cout<< 10 您在输出中获得10,您不需要自己的任何转换

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

ltoa 没有为字符串分配任何内存,这是不健康的,因为你可能注意到。你使用一个局部变量(相同的,对于所有500个数组成员),你尝试访问后,你退出该函数 - 一个大无,其未定义的行为。

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.

和:

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

否。不仅不需要 - 不应该在那里!当在C ++中使用 new delete 时,永远不要 malloc ,这是一个C函数。

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.

这篇关于int to string,char * itoa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆