gpt4 book ai didi

c++ - int 到 char* 和内存分配

转载 作者:行者123 更新时间:2023-11-30 04:28:30 25 4
gpt4 key购买 nike

这很可能很简单,但如果有人能解释最简单的方法来让“sval”包含字符串“$1” - “$500”用于数组索引 0-499。在下面的代码中,但是 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 = new data_t[500];
f1(&d);
}

/* code for function f1 to fill in array begins */
void f1(data_t **d)
{
char str[5];
for (int i=0; i<500; i++)
{
(*d)[i].ival = i+1;
itoa (i+1,str,10);
(*d)[i].sval = str;
}
}

itoa 似乎也被折旧了,但这是我用 google 搜索 int to string 时得到的结果

或者...尝试使用 stringstream 我仍然遇到问题,而且我无法在前面获得“$”,但是...

#include<iostream>
#include<sstream>
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(sizeof(data_t)*500)); //for legacy c
d = new data_t[500];
f1(&d);
}

/* code for function f1 to fill in array begins */
void f1(data_t **d)
{
stringstream ss;
char *str;

for (int i=0; i<500; i++)
{
(*d)[i].ival=i+1;
ss << i;
str = ss.str();
(*d)[i].sval= str;
}
}

char * 和 string 不能很好地协同工作......又一次......我仍然不确定如何在整个事情前面获得“$”......呃

哦...如果有帮助...这是给出的代码:以及我的要求下面的程序包含一个 data_t 类型的结构数组。给出了 data_t 类型的变量“d”的声明。将逻辑写入主程序,为变量“d”分配内存,使其包含一个包含 500 个元素的数组,每个元素都是 data_t 类型。不要费心释放内存或测试 malloc 的返回值是否为 NULL。然后,编写函数 'f1' 来填充数组的 500 个元素中的每一个,使得整数字段 'ival' 的值分别为数组索引 0-499 的值 1-500,字符串字段 'sval' 包含字符串“$1” – “$500”分别对应数组索引 0-499。在主程序末尾调用函数“f1”。

typedef struct data_t {
int ival;
char *sval;
} data_t;
main()
{
data_t *d; /* declaration for an array of data_t structures */
/* allocate memory for a 500 element array of structures begins */
/* allocate memory for a 500 element array of structures ends */
f1(&d); /* function call to fill in array */
}
/* code for function f1 to fill in array begins */
f1(data_t **d)
{
}
/* code for function f1 to fill in array ends */

最佳答案

void f1(data_t **d)
{
char str[5];
for (int i=0; i<500; i++)
{
(*d)[i].ival = i+1;
itoa (i+1,str,10);
(*d)[i].sval = str;
}
}

您正在指定每个 sval 成员指向同一个数组 (str)。也就是说,(*d)[i].sval 将指向所有元素的相同内存位置。更糟糕的是,它们都指向一个 local 数组,当 f1 返回时,该数组将变成垃圾。

如果您希望每个数组元素的 sval 成员指向它自己的字符串,您必须自己显式分配内存(并在以后显式释放它)。

void f1(data_t **d)
{
for (int i=0; i<500; i++)
{
char *str = malloc(5);
if (str == NULL) {
abort(); // Or fail gracefully somehow.
}

(*d)[i].ival = i+1;
itoa (i+1,str,10);
(*d)[i].sval = str;
}
}

关于c++ - int 到 char* 和内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10086932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com