I was trying out a simple program to understand how to use a pointer to an array of pointers to structure.
I wrote this small program:
#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");
}
The program compiled and executed properly and I got this output:
0
1
2
3
4
5
val: hi
val: bye
val: see you
6
7
Program successfully completed
But while compiling I was getting these warnings on deprecated conversion from string to char*
so I decided to change the char*
in my struct to std::string
. I changed the program into:
#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");
}
Now The program compiled properly but I got a segmentation fault(core dumped)
on running. Not even the first printf("0");
got displayed. Can anyone explain me what mistake am I doing here?