[英]int to string, char* itoa
trying to get 'sval' to contain the string “$1” – “$500” for array indexes 0-499.试图让 'sval' 包含数组索引 0-499 的字符串“$1” – “$500”。 in the following code, however itoa is giving me strange strings in the code below:在下面的代码中,但是 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;
}
}
it also seems itoa has been depreciated, but that was what i got when i googled int to string itoa 似乎也被贬值了,但那是我用谷歌搜索 int to string 时得到的结果
You don't need ltoa
, cout
should be just fine.你不需要ltoa
, cout
应该就好了。 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当你执行cout << 10
时,你会在 output 上得到“10”,你不需要自己进行任何转换
You, on the other hand, do ltoa
without allocating any memory for the strings, which is not healthy as you have probably noticed.另一方面,您执行ltoa
时没有为字符串分配任何 memory,您可能已经注意到,这是不健康的。 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.您使用一个局部变量(相同,对于所有 500 个数组成员),您在退出 function 后尝试访问它 - 一个很大的禁忌,它的未定义行为。
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.在 C++ - 使用new
和delete
时,从不使用malloc
,这是 C function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.