gpt4 book ai didi

c++ - 在动态分配的结构中使用 std::string 时出现段错误

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

<分区>

我正在尝试一个简单的程序来了解如何使用指向结构指针数组的指针。

我写了这个小程序:

#include <stdio.h>
#include <stdlib.h>

struct A
{
char* a1;
};

void fn1(A **d, int n)
{
printf("5 \n");
for(int i=0;i<n;i++)
{
printf("val: %s \n",d[i]->a1);
}
printf("6 \n");
}
int main(int argc, char **argv) {
printf("0 \n");
A *a,*b,*c;
printf("1 \n");
a = (A*)malloc(sizeof (A));
b = (A*)malloc(sizeof (A));
c = (A*)malloc(sizeof (A));
printf("2 \n");
a->a1 = "hi";
b->a1 = "bye";
c->a1 = "see you";
printf("3 \n");
A *d[] = {a,b,c};
printf("4 \n");
fn1(d,3);
printf("7 \n");
printf("Program successfully completed \n");
}

程序正确编译和执行,我得到了这个输出:

0 
1
2
3
4
5
val: hi
val: bye
val: see you
6
7
Program successfully completed

但是在编译时,我收到了关于 deprecated conversion from string to char* 的警告,所以我决定将结构中的 char* 更改为 std: :字符串。我把程序改成了:

#include <stdio.h>
#include <string>
#include <stdlib.h>

struct A
{
std::string a1;
};

void fn1(A **d, int n)
{
printf("5 \n");
for(int i=0;i<n;i++)
{
printf("val: %s \n",d[i]->a1.c_str());
}
printf("6 \n");
}
int main(int argc, char **argv) {
printf("0 \n");
A *a,*b,*c;
printf("1 \n");
a = (A*)malloc(sizeof (A));
b = (A*)malloc(sizeof (A));
c = (A*)malloc(sizeof (A));
printf("2 \n");
a->a1 = "hi";
b->a1 = "bye";
c->a1 = "see you";
printf("3 \n");
A *d[] = {a,b,c};
printf("4 \n");
fn1(d,3);
printf("7 \n");
printf("Program successfully completed \n");
}

现在程序已正确编译,但我在运行时遇到了段错误(核心转储)。甚至没有显示第一个 printf("0");。谁能解释一下我在这里犯了什么错误?

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