[英]int to string, char* itoa
試圖讓 'sval' 包含數組索引 0-499 的字符串“$1” – “$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 似乎也被貶值了,但那是我用谷歌搜索 int to string 時得到的結果
你不需要ltoa
, cout
應該就好了。 為什么需要將數字及其字符串表示形式保留在數組中? 當你執行cout << 10
時,你會在 output 上得到“10”,你不需要自己進行任何轉換
另一方面,您執行ltoa
時沒有為字符串分配任何 memory,您可能已經注意到,這是不健康的。 您使用一個局部變量(相同,對於所有 500 個數組成員),您在退出 function 后嘗試訪問它 - 一個很大的禁忌,它的未定義行為。
和:
d=static_cast<data_t*>(malloc(500)); //is this even needed?
d = new data_t[500];
不,不僅不需要——根本不應該存在! 在 C++ - 使用new
和delete
時,從不使用malloc
,這是 C function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.