-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
infor(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.– anonimo
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?
– Enzo Nunes
No, the scanf can go beyond the allocated memory.
– anonimo
I get it. I’ll try here, thank you.
– Enzo Nunes