配列インデックス0-499の文字列 "$ 1" - "$ 500"を含むように 'sval'を取得しようとしています。次のコードでは、しかし、itoaは私に以下のコードで奇妙な文字列を与えている:また、itoaは減価償却されているようだint to string、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;
}
}
を、それは、私は、文字列
なぜですか?なぜ?** d' ?????ちょうどあなたが '(* d)[i]'をすることができるように?本当に?! – littleadv
'std :: string'を使うだけです。 –
'malloc'と' new'の両方を使うべきではありません。ちなみに、 'malloc'は' sizeof(data_t)* 500'で '500 'ではなく呼び出されるべきです。しかし、C++で 'malloc'を使用しないでください.Cとの互換性のためにしか使用できませんでした。 – vsz