0

The aim is to include an array of an structure inside an other array of an other structure. Both structure arrays should be declared and initialised seperate. The questeions and answeres suggested as similarly only had one component of my questeion but not this or an similar combination. The code I added here is just a simplified example. All array sizes and elements are known before execution.

This is the example code, that can not be compiled "Segmentation fault":

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

struct student_course_detail
{
    int  course_id;
    char course_name[50];
};

struct student_detail 
{
    int id;
    char name[20];
    // structure within structure
    struct student_course_detail *course[2]; 
}stu_data[2], *stu_data_ptr[2];


struct student_course_detail course_data[2] = {
  {71145, "Course 1"}, 
  {33333, "Course 2"},
}; 

struct student_detail stu_data[2] = {
    {1, "Anna", &course_data[1]},
    {2, "Tom", &course_data[2]}
};


int main() 
{
    stu_data_ptr[2] = &stu_data[2];

    printf(" Id is: %d \n", stu_data_ptr[0]->id);
    printf(" Name is: %s \n", stu_data_ptr[0]->name);


    printf(" Course Id is: %d \n", 
                         stu_data_ptr[0]->course[0]->course_id);
    //printf(" Course Name is: %s \n", 
    //                 stu_data_ptr[0]->course[0]->course_name);
    //printf(" Course Id is: %d \n", 
    //                     stu_data_ptr[0]->course[1]->course_id);
    //printf(" Course Name is: %s \n", 
    //                  stu_data_ptr[0]->course[1]->course_name);

    return 0;
}

Link to the code-example: https://www.onlinegdb.com/Hk2NQ42OU

2 Answers 2

1

The structure member course is an array of two pointers to struct student_course_detail.

Judging from how you attempt to initialize it, it should not be an array, but a plain pointer to struct student_course_detail:

struct student_course_detail *course;  // Pointer to a single student_course_detail structure

You have similar problems in other places (stu_data_ptr).

Also don't forget that array indexes are zero base, so &course_data[2] is out of bounds of the course_data array.

Sign up to request clarification or add additional context in comments.

1 Comment

I got the code running in the way I was looking for. (with your hints) link but I still get the warning: main.c:32:18: warning: assignment from incompatible pointer type How to get this pointer assignment right?
0

When you define an array with n elements, the elements' index ranges from 0 to n-1.

So in this case all arrays are of size 2, so the elements you have are indexed by 0 and 1.

For instance this is illegal:

stu_data_ptr[2] = &stu_data[2]; //illegal

you should can either do:

stu_data_ptr[1] = &stu_data[1];

or

stu_data_ptr[0] = &stu_data[0];//use this, since you use stu_data_ptr[0] later

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.