0

This code under returns "segmention fault".

struct aluno
{
    char nome[80];
    float nota;
};

struct classe
{
    struct classe* aluno_anterior;
    struct classe* aluno_posterior;
    struct aluno aluno;
};

struct classe *alunos;

void inicializar_classe(void)
{
    alunos->aluno_anterior = NULL; //here occurs the segmentation fault
    alunos->aluno_posterior = NULL;
}

How can I initialize the fields aluno_anterior and aluno_posterior to NULL correctly?

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 1
    You have to initialize `alunos` first. – tkausl Oct 04 '21 at 00:25
  • 1
    A pointer needs something to point to. It's nothing other than a memory address. You cannot drive to a random address and deliver a package to the resident that lives on the 3rd floor, because there may not be a 3 story building at that address, or it might not be a residence, or it might be uninhabited. – Cheatah Oct 04 '21 at 00:30

1 Answers1

2

In the code shown, alunos is initialized by default to a null pointer. It points “nowhere,” so alunos->aluno_anterior is invalid code. alunos->aluno_anterior means “The aluno_anterior member in the structure that alunos points to,” but alunos does not point to any structure, so using that expression is invalid.

To fix that, allocate enough memory for a struct classe and set alunos to point to that memory:

alunos = malloc(sizeof *alunos);
if (!alunos)
{
    fprintf(stderr, "Error, failed to allocate memory.\n");
    exit(EXIT_FAILURE);
}

To declare the identifiers used above, insert:

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

in the source code, outside of any function and before the identifiers are used.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312