我正在尝试一个简单的程序来理解如何使用指向结构指针数组的指针。
我写了这个小程序:
#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::string
。我把程序改成了:
#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");
}
现在程序已正确编译但我在运行时得到segmentation fault(core dumped)
。甚至没有显示第一个printf("0");
。谁能解释一下我在这里犯的错误?
答案 0 :(得分:1)
malloc
不适合创建非POD对象。它分配内存但不调用任何构造函数。所以你的行a->a1
访问一个尚未构造的字符串,导致未定义的行为。
要正确分配和构造对象,请使用:
a = new A;
在任何C ++程序中使用malloc
都是不好的风格(最多)