I'm having a problem with the following program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Persona {
char *nombre, *apellido;
int edad;
};
int main(int argc, char const *argv[])
{
int total_personas = 0;
printf("Cuantas personas vas a ingresar?\n");
scanf("%d", &total_personas);
struct Persona *personas;
personas = (struct Persona *) malloc(total_personas * sizeof(struct Persona));
for (int i = 0; i < total_personas; i++) {
char nombre[256], apellido[256];
int edad;
printf("Nombre: ");
scanf("%s", nombre);
printf("Apellido: ");
scanf("%s", apellido);
printf("Edad: ");
scanf("%d", &edad);
struct Persona p = {nombre, apellido, edad};
personas[i] = p;
}
printf("Id\tNombre\tApellido\tEdad\n");
for (int i = 0; i < total_personas; i++) {
printf("%d\t%s\t%s\t%d\n",
i + 1, personas[i].nombre, personas[i].apellido, personas[i].edad);
}
return 0;
}
Basically what I want it to do is the following:
- I want to declare a dynamic array of Persona structs.
- Then I want to capture the information from the user using
scanf
- Then I want to display the captured information back to the user.
1 & 2 work "fine". The problem is that my last nombre
and apellido
(of char[256]
each) are overriding my first two inputs:
This is what it shows:
Cuantas personas vas a ingresar?
2
Nombre: alan
Apellido: chavez
Edad: 32
Nombre: jaun
Apellido: perez
Edad: 54
Id Nombre Apellido Edad
1 jaun perez 32
2 jaun perez 54
This is what it should be:
Cuantas personas vas a ingresar?
2
Nombre: alan
Apellido: chavez
Edad: 32
Nombre: jaun
Apellido: perez
Edad: 54
Id Nombre Apellido Edad
1 alan chavez 32
2 jaun perez 54
It only works for the variable edad
and I'm not really sure why. Any pointers in the right direction would be greatly appreciated.
When I try to use the strncpy
function I get Segmentation fault: 11
This is how I'm using it:
printf("Nombre: ");
scanf("%s", nombre);
strncpy(personas[i].nombre, nombre, strlen(nombre));