When I tried to use only INT arguments, it worked perfectly, but when I try to use strings I always get "Segmentation Fault" and I don't know why. I know it might be a silly mistake, but would anyone care to explain it to me, please?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct cliente{
char *nome;
int idade;
}t_cliente;
int main(){
t_cliente *vet;
int qtdCliente, i, j;
scanf("%d", &qtdCliente);
vet=(t_cliente*)malloc(qtdCliente*sizeof(t_cliente));
for(i=0; i<qtdCliente; i++){
scanf("%s", vet[i].nome);
scanf("%d", &vet[i].idade);
}
for(j=0; j<qtdCliente; j++){
printf("%s\n", vet[j].nome);
printf("%d\n", vet[j].idade);
printf("\n");
}
free(vet);
return 0;
}
vet=(t_cliente*)malloc(qtdCliente*sizeof(t_cliente));
(and the cast is both unnecessary and unwise in C) will give you an array of structures, each containing the two fields nome and idade.
However, nome in each structure will be set to an arbitrary value so the statement:
scanf("%s", vet[i].nome);
will almost certainly attempt to write to memory that it shouldn't be writing to.
Assuming you know what the maximum size will be for the first field, you would be better off defining it as something like:
#define MAXNOME 50
typedef struct cliente{
char nome[MAXNOME];
int idade;
}t_cliente;
That way, the memory you will attempt to write to will at least be valid.
However, people who use scanf("%s",...) often don't realise how bad a practice it is. It can lead to buffer overflow problems since there is no way to specify a limit on the characters that will be written to the buffer. There are much safer ways to do this (get user input), such as the one found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With