ERROR WHEN GIVING CHAR PRINTF

Asked

Viewed 51 times

-1

Hello, I’m trying to do an activity using struct, ?

/* Program to display Nested Structures in C Programming */
#include<stdio.h>
#include<string.h>
#include <stdlib.h>

struct endereco
{
  char logradouro;
  int numero;
  char bairro;
};

typedef struct
{
  int matricula;
  char nome[20];
  struct endereco add;
}emp3;

emp3 lerData(int matricula, char nome)
{ 
    emp3 c;
    c.matricula = matricula; 
    c.nome[20] = nome;
    return c; 
}
void imprimeData(emp3 emp) 
{
   printf("A matricula armazenada foi: %d\n", emp.matricula);
   printf("O nome armazenado foi: %s\n", emp.nome);

}

int main() 
{
    emp3 emp;
    
	printf("Digite a matricula: ");
    scanf("%d", &emp.matricula);
    printf("Digite o nome: ");
    scanf("%s", &emp.nome);;
    
    emp = lerData(emp.matricula,emp.nome); 
    imprimeData(emp);
    return 0;

}


is not printing in the print function

  • Are you sure that your patio and neighborhood contains a single character?

1 answer

1

The problem is here:

emp3 lerData(int matricula, char nome)
{ 
    emp3 c;
    c.matricula = matricula; 
    c.nome[20] = nome;
    return c; 
}

Change for:

emp3 lerData(int matricula, char *nome)
{ 
    emp3 c;
    c.matricula = matricula; 
    strcpy(c.nome, nome);
    return c; 
}


Explanation

In your code you are converting a string to character: emp = lerData(emp.matricula,emp.nome); and assigned this character to c.nome[20] in lerData that will give a stack burst by the stack is between 0 and 19.

What you should do is adjust lerData to receive a string then using strcpy copy the string to c.name in lerData.

Browser other questions tagged

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