-2
int main()
{
  int i;
  struct student* a[4];

  a[0]->id = 20;
  a[0]->age= 22;

  a[1]->id = 23;
  a[1]->age= 24;

  a[2]->id = 25;
  a[2]->age= 26;

  a[3]->id = 27;
  a[3]->age= 28;

  for(i=0;i<4;i++)
  {  
    printf("%d %d \n",a[i]->id,a[i]->age);
  }

  return 0;
}

Without the for loop the values can be printed directly but inside for loop the output showing is segmentation fault.

Umaiki
  • 354
  • 2
  • 14

2 Answers2

3

As Umaiki has already said, you access memory you have never allocated. In contrast to his answer, I provide a different approach:

First, this is how we define the struct:

typedef struct {
    int id;
    unsigned int age;
} student;

after that, we can allocate the students array in the main method like this:

student* a = malloc(4 * sizeof(student));

Now we can access the student at <index> like so:

a[<index>].id = <value>;
a[<index>].age= <value>;

And lastly, here is a complete example of what (I think) you want to achieve, combing all the snippets I have shown above and including the call to free (which is negligible in this case, because you exit directly thereafter, but it's something you should never forget):

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

typedef struct {
    int id;
    unsigned int age;
} student;

int main() {
    student* a = malloc(4 * sizeof(student));

    a[0].id = 20;
    a[0].age = 22;

    a[1].id = 23;
    a[1].age = 24;

    a[2].id = 25;
    a[2].age = 26;

    a[3].id = 27;
    a[3].age = 28;

    for (int i = 0; i<4; i++)
    {
        printf("%d %d \n", a[i].id, a[i].age);
    }

    free(a);

    return 0;
}
Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
2

Your main problem is that you are trying to access memory you did not allocated.

Start there: https://www.programiz.com/c-programming/c-dynamic-memory-allocation and Using Dynamic Memory allocation for arrays.

You create a pointer and do not initialize it, so when you try to access the memory it is pointing to, a very common segmentation faultappears...

I don't know what you want to do, but in order to correct your segfault, in this case you have to make a forloop to initialize your array of pointers :

struct student  ab[4];
struct student* a[4]
/* ... code ...*/
for (i=0; i<4; i++)
{
  a[i] = &ab[i];
}
/* ... code ...*/
Umaiki
  • 354
  • 2
  • 14