Segmentation fault when trying to access array of pointer to structure [duplicate]

  array-of-structures, c++, pointers, structure

this is my sample code which is similar to my project, to simplify I created this dummy program.

#include <iostream>

using namespace std;
 struct str1{
      int a1;
   };
 
void fun(str1 *x);

int main()
{
  str1 s;
   fun(&s);
    cout<<"print "<<s.a1<<endl;
    return 0;
}

void fun(str1 *x){
    struct test{int c1;}tst;
    tst.c1 =7;
    for(int i= 0; i<9;i++){
    x->a1=tst.c1;
    }
};

i want to create 5 copies of the struct which is something like

#include <iostream>

using namespace std;
 struct str1{
      int a1;
   };
 
void fun(str1 *x);

int main()
{
  str1 s;
   fun(&s);
    cout<<"print "<<s.a1<<endl;
    return 0;
}

void fun(str1 *x){
    struct test{int c1;}tst;
    tst.c1 =7;
    for(int i= 0; i<9;i++){
    x[i]->a1=tst.c1;                         % I want to create something like this
    }
};

which means s[0].a1,s[1].a1…. values is assigned to tst.c1 result.

Can Anyone help me with this.

Thank You.

Source: Windows Questions C++

LEAVE A COMMENT