Matheus Dias
Matheus Dias

Reputation: 17

How to print a value in a struct pointer pointed for other struct?

Considering that i have two structs, where one point to other, how could i print a vallue from the second struct, caliing the first?

A brief explanation of the program bellow:

NODE, a struct that points to itselft to make a pile and to a generic pointer ALUNO, the struct that the generic pointer in NODE will point to createNode, function that allocates memory for the nodes preencherNode, fills the pointer of node with the respective ALUNO pushNode, creates a new node, pointing to the last created one, making a pile criarAluno, allocates memory for ALUNO and fills it camps.

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

typedef struct
{
    int id;
    float media;
} ALUNO;

typedef struct node
{
    void *pointer;
    struct node* link;
} NODE;

NODE* createNode(void)
{
    NODE* topo;
    topo=(NODE*)malloc(sizeof(NODE));

    topo->pointer = NULL;
    topo->link = NULL;
    return(topo);
}

NODE* pushNode (NODE* topo)
{
    NODE* novo;
    novo=createNode();

    novo->link=topo;
    topo = novo;

    return(topo);
}

NODE* preencherNode (NODE* topo, ALUNO* data)
{
    topo->pointer=data;
    return(topo);
}

ALUNO* criarAluno(FILE* v)
{
    ALUNO* aln;
    aln=(ALUNO*)malloc(sizeof(ALUNO));

    int x;
    float y1,y2;
    fscanf (v, "%d %f %f",&x,&y1,&y2);

    aln->id=x;
    y1=(y1+y2)/2;
    aln->media=y1;

    return(aln);
}

void printData (NODE* topo)
{
    NODE* aux;
    aux=topo;

    ALUNO* aln;

    while(aux->link!=NULL)
    {
        aln=((ALUNO*)(aux->link));

        printf("ID: %d \n",aln->id);
        printf("Media: %f \n",aln->media);
        printf("........................ \n");

        aux=aux->link;
    }
}

void main ()
{
    FILE *doc;
    doc = fopen("documento.txt","r");
    if (doc==NULL){
        printf("Nao ha como abrir o arquivo");
        return(-1);
    }
    NODE *pilha;
    pilha=createNode();

    ALUNO* aluno;
    int x;

    for(x=0;x<11;x++)
    {
        aluno=criarAluno(doc);
        pilha=preencherNode(pilha,aluno);
        pilha=pushNode(pilha);
    }

    printData(pilha);
}

So now, the function printData, is printing the allocated space memory of the value i want, but not the value.

Upvotes: 0

Views: 115

Answers (1)

GilesW
GilesW

Reputation: 515

Given as stated in question that you have NODE *node....

ALUNO *aluno;
aluno = (ALUNO *)(node->pointer)
printf("%d", aluno->id)

Upvotes: 1

Related Questions