Error printing a structure

0

The program has to read and display data from a structure, the program does not throw error but in the exit it appears the name after garbage (spaces without assigning) and the last name when it is shown How can this be solved?

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

typedef struct {
    long int cedula;
    char nombre[15];
    char apellido[15];
    char telefono[8];
}Persona;

void cargar(Persona &per) {
    printf(" Ingresar la c%cdula: ",130);
    scanf("%ld",&per.cedula);
    printf("Ingresar el nombre: ");
    scanf("%s",&per.nombre[15]);
    printf("Ingresar el apellido: ");
    scanf("%s",&per.apellido[15]);
    printf("Ingrese el tel%cfono: ",130);
    scanf("%s",&per.telefono[8]);
}

void mostrar(Persona &per) {
    printf("\n\nLa cedula es: %ld\n",per.cedula);
    printf("El nombre es: %s\n",per.nombre);
    printf("El apellido es: %s\n",per.apellido);
    printf("El tel%cfono es: %s\n",130,per.telefono);
}

int darCedula(Persona per){
    return per.cedula;
}

int main() {
    Persona per;
    cargar(per);
    mostrar(per);
    darCedula(per);
    getch();
    return 0;
}
    
asked by Alejandro Caro 03.12.2017 в 00:31
source

1 answer

0

The problem is caused by the instructions of the type:

scanf("%s",&per.nombre[15]);

In that instruction you are indicating that you start saving the data from position 15 of the array.

What you should do is use &per.nombre[0] , or simply per.nombre without & ni [] .

Replace your function load with the following:

void cargar(Persona &per) {
    printf(" Ingresar la c%cdula: ",130);
    scanf("%ld",&per.cedula);
    printf("Ingresar el nombre: ");
    scanf("%s",per.nombre);
    printf("Ingresar el apellido: ");
    scanf("%s",per.apellido);
    printf("Ingrese el tel%cfono: ",130);
    scanf("%s",per.telefono);
}

Note:

When you declare an array: algun_tipo algun_array[n] , you are telling it to create n memory spaces of type algun_tipo contiguous:

|__|__|__|__|__|__|__|
 0   1  2  ....    n

And to access the i-th position you use the operator [] : some_array [i], so it's a variable, so when you use the &algun_array[i] instruction, you're getting the memory address of the i-th finished. scanf() uses the secuandarios arguments to save the data, so it only needs its memory position, and in your case you are passing it the i-esima position within the array so in the end you can be writing in memory that you have not separated (this can cause problems). The same can happen with printf() since you may also be reading unassigned memory, on garbage.

    
answered by 03.12.2017 / 00:44
source