Problem with DYNAMIC ALLOCATION with char pointer in structs

Asked

Viewed 58 times

-1

I have the following problem:

I must create a program that will register an N number of students and the maximum size of each student’s name is M. I must use the following structure:

struct Aluno{
  int matricula;
  char *nome;
};

And I must implement the functions:

Aluno* aloca_vetor_alunos(int tamanho_vetor, int tamanho_nome);

void libera_memoria_alunos(int tamanho_vetor, Aluno* alunos);

To create the student array I must use dynamic memory allocation. With this, I made the following code:

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

struct Aluno{
    int matricula;
    char *nome;
};

struct Aluno* aloca_vetor_alunos(int tamanho_vetor, int tamanho_nome){
    struct Aluno* ptr1;

    ptr1 = (struct Aluno*) malloc(sizeof(struct Aluno) * tamanho_vetor);
    ptr1->nome = (char*) malloc(sizeof(char) * tamanho_nome);

    return ptr1;
}

void libera_memoria_alunos(int tamanho_vetor, struct Aluno* alunos){

}

int main(){
    int N, M;
    int i;
    struct Aluno* alunos;

    printf("Quantos alunos serao cadastrados? ");
    scanf("%d", &N);
    printf("Tamanho maximo do nome? ");
    scanf("%d", &M);

    alunos = aloca_vetor_alunos(N, M);

    for(i = 0; i < N+1; i++){
        printf("Matricula: ");
        scanf("%d", &alunos[i].matricula);
        printf("Nome: ");
        scanf("%s", alunos[i].nome);
    }

    for(i = 0; i < N; i++){
        printf("%d - %d", i, alunos[i].matricula);
        printf("%d - %s", i, alunos[i].nome);
        printf("\n");
    }

    return 0;

}

However, I am facing problems reading and printing the data. The program only reads 2 students and then closes and does not print the data.

  • What is the meaning of this N+1 in for(i = 0; i < N+1; i++){? Another point: if you specified a maximum size for the name (M) then I think I should limit the size of the names given.

  • I think I wrote the (+1) by mistake. And as for the limitation of names, I believe I already did this when I allocate memory for the name no?

  • No, the scanf can go beyond the allocated memory.

  • I get it. I’ll try here, thank you.

1 answer

0


The problem is that the code snippet below allocates memory to only the pointer nome of the first vector element.

ptr1->nome = (char*) malloc(sizeof(char) * tamanho_nome);

The right would be to iterate through all elements and allocate to each one. As below:

ptr1 = (struct Aluno*) malloc(sizeof(struct Aluno) * tamanho_vetor);

for(int i = 0; i < tamanho_vetor; i++)
{
    ptr1[i].nome = (char*) malloc(sizeof(char) * tamanho_nome);
}

Could also use the function fgets to limit the input size of the name.

fgets(alunos[i].nome, M, stdin);
  • Wow, I hadn’t thought of that. I checked here and it worked. Thank you!!

  • Do not forget to mark as accepted if the answer was helpful.

Browser other questions tagged

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