Why can’t I print content in Chained List

Asked

Viewed 70 times

0

Good evening, I have a problem with a college job. I need to create a linked list that receives student records. I created a function to register, however, I can not print, externally, the contents of it using the pointer of the first. I wonder why this is happening.

For example, within the scope of the function it can print with (*((*a).alunoPosterior)).nome), but when I go outside I can’t do it using (*(a.alunoPosterior)).nome.

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

#define length 100

typedef struct aluno {
    int matricula;
    int telefone;

    double n1;
    double n2;
    double n3;
    double media;

    char nome[length];
    char email[length];

    struct aluno *alunoAnterior;
    struct aluno *alunoPosterior;
} Aluno;

void criarAluno(Aluno *a);

int main() {
    setlocale(LC_ALL, "Portuguese");

    Aluno a;

    gets(a.nome);
    criarAluno(&a);

    printf("NOME A = %s\nNOME B = %s", a.nome,  (*(a.alunoPosterior)).nome);

    return 0;
}

/**
    A função cria um struct de Aluno. Em seguida, vincula o struct recém-criado ao ponteiro (*a)
    do mesmo tipo que veio através do parâmetro.
*/
void criarAluno(Aluno *a) {
    Aluno b;

    fflush(stdin);

    printf("Insira o nome do aluno: ");
    gets(b.nome);

  /*  printf("\nInsira o número de matrícula do aluno: ");
    scanf("%d", &b.matricula);

    printf("\nInsira o número de telefone do aluno: ");
    scanf("%d", &b.telefone);

    printf("\nInsira a Nota 1: ");
    scanf("%d", &b.n1);

    printf("\nInsira a Nota 2: ");
    scanf("%d", &b.n2);

    printf("\nInsira a Nota 3: ");
    scanf("%d", &b.n3);

    b.media = (b.n1 + b.n2 + b.n3)/3;*/

    (*a).alunoPosterior = &b;

    printf("%s\n\n", (*((*a).alunoPosterior)).nome);
    b.alunoAnterior = a;
}

Does anyone have any idea what I can do?

  • Your question is not very clear I’m having trouble understanding what you want, you could edit it and be more objective.

  • Edited Question!

1 answer

0

I was able to respond when I replaced the statement Aluno b for :

Aluno *b = (Aluno*) malloc(sizeof(Aluno));
  • You must not cast a malloc.

  • Why shouldn’t I?

  • 1

    Redundancy.You end up repeating what is bad, decreasing readability or in the worst cases by hiding a mistake. You can read more here http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc notice is in English.

  • 1

    Hard drive is not how you allocate memory to your object. Do it this way aluno = (struct Aluno *) (malloc(sizeof(struct Aluno) * 1));. The * points to the memory content is used to access data from a pointer.

  • Excuse the ignorance but... why multiply the sizeof by 1?

  • It’s just a convention to say it’s going to have the size of 1, it’s not necessary, it’s just representative.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.