试图让'sval'包含数组索引0-499的字符串“$ 1” - “$ 500”。在下面的代码,但是itoa是给我下面的代码奇怪的字符串:int到字符串,char * 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 INT串
为什么?告诉我,为什么'** d' ?????只是为了让你可以做'(* d)[i]'?真?! – littleadv 2012-04-10 06:06:17
只需使用'std :: string'。 – 2012-04-10 06:06:53
你不应该同时使用'malloc'和'new'。顺便说一句,'malloc'应该用'sizeof(data_t)* 500'而不是'500'来调用。但更好的是,你不应该在C++中使用'malloc',它只与C兼容。 – vsz 2012-04-10 06:09:28