Query with Pointer for Struct in C

Asked

Viewed 183 times

0

I am trying to solve an exercise for the college, where the statement requests that I receive a record, with two fields as input data. A vector field for storing name and another for storing matricula. I must also declare a pointer to the heterogeneous data structure, and use this pointer when reading data and printing data on the screen.

My code does not show error in Visual Studio, but when you open the command prompt it generates the error message :

Erro

Follows my code :

#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
//Programa Principal


struct cadastro {//Declaração da struct para armazenamento de registro com 2 campos
    char nome[40];
    int ru;
};
struct cadastro aluno, *pont1;//variavel aluno referenciando a struct

int main() {
    //Titulo do programa
    printf("---------Cadastro de aluno----------\n");
    printf("\n");

                          //Entrada de informações pelo usuário
    printf("Digite seu nome: ");
    fflush(stdin);//Limpa dados armazenados na memória
    fgets((*pont1).nome, 40, stdin);//Referencia onde na struct deve ser armazenada a informação
    printf("\n");


    printf("Digite seu RU: ");
    scanf_s("%d", (*pont1).ru);
    //Print de dados informados pelo usuário
    printf("\n");
    printf("---------Dados Informados-----------\n");
    printf("\n");
    printf("O nome digitado foi: %s\n", (*pont1).nome);
    printf("\n");
    printf("O RU digitado foi: %d\n", (*pont1).ru);
    printf("\n");
    //Fim do programa
    system("pause");
    return 0;
}

Everywhere I searched, I saw the use of pointers to predefined values within the code, however, I’m trying to make the same function run with the user information input.

Can someone help me?

  • 1

    You need to allot memory to the structure. In this case, you are pointing to nothing valid. Do at startup something like pont1 = malloc(sizeof cadastro);. Don’t forget to give free(pont1) at the end. And read about memory allocation.

  • Remember that you can mark one as the correct answer. If you don’t know how, see here on tour and already learn a little more about the stack.

1 answer

1


You need to allocate memory to your pointer. The way you used it, you are pointing nowhere valid. With the use of the function malloc we allocate a space in memory for you to use.

struct cadastro *pont1;// Ponteiro de cadastro

int main() {
    //Titulo do programa
    printf("---------Cadastro de aluno----------\n");
    printf("\n");

    // Aqui você está alocando memória para o cadastro
    // A partir deste momento, um espaço na memória é reservado para a sua estrutura
    // Como pode ver, o malloc aceita como argumento o tamanho, por isso, foi utilizado sizeof
    // Assim alocamos o espaço necessário para a estrutura
    pont1 = (cadastro*)malloc(sizeof cadastro);

    // Se quisesse alocar espaço para vários cadastros, multiplique pela quantidade
    //pont1 = (cadastro*)malloc(sizeof cadastro * QUANTIDADE);
    // E voCê pode acessar assim:
    // pont1[indice].nome = "Meu nome";

    printf("Digite seu nome: ");
    fflush(stdin);

    // Você não precisa fazer (*pont1), você pode usar simplesmente pont1->
    fgets(pont1->nome, 40, stdin);
    printf("\n");

    printf("Digite seu RU: ");
    scanf_s("%d", &pont1->ru);

    //Print de dados informados pelo usuário
    printf("\n");
    printf("---------Dados Informados-----------\n");
    printf("\n");
    printf("O nome digitado foi: %s\n", pont1->nome);
    printf("\n");
    printf("O RU digitado foi: %d\n", pont1->ru);
    printf("\n");

    system("pause");

    free(pont1);
    return 0;
}

I commented on the code with pertinent information

  • got it now. All the dynamic allocation tutorials I was seeing were confusing me more, as you put it I understood. Regardless of how many variables my struct has, can I allot memory by referencing malloc by struct size argument ? Thank you so much for your help.

  • Important is that you also remember the function free that will release the resources allocated by you. This is called memory leak. Try to know this well too so you don’t miss at the front. If it is a larger application in which dynamic allocation is used, making the application grow in memory all the time

Browser other questions tagged

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