3
I’m having trouble assigning a value to a variable of type char
of a struct
I’m doing the following
#include <stdio.h>
typedef struct Animal{
char nome[5]; // indiquei que a variavel nome tem 5 caractes
int idade;
}Cachorro;
int main(){
Cachorro Dog;
Dog.idade = 9;
Dog.nome = "Salfr"; // tento atribuir "Salfr" a minha variavel
printf("'%s' '%d'", Dog.nome, Dog.idade);
return 0;
}
only that an error of Segmentation failure
when I compile appears test.c|11|warning: assignment makes integer from pointer without a cast|
and when I run it appears Segmentation Fault
now when I point out that my name variable char and a pointer works usually follows below
#include <stdio.h>
typedef struct Animal{
char *nome;
int idade;
}Cachorro;
int main(){
Cachorro Dog;
Dog.idade = 9;
Dog.nome = "Salfr";
printf("'%s' '%d'", Dog.nome, Dog.idade);
return 0;
}
when compiling and executing I get the following return
'Safari' '9'
my problem is related to the char type related to this my question Is there a problem assigning a value to a pointer? I know this method is not advisable but it was the only way it worked until the moment someone knows why it is happening Segmentation Fault
in the first example?
use the function strcpy() to copy the contents of the string to its variable
nome
.– gato
In the links below you will find questions and answers that although they are not the same that you have can help you find out why your code misbehaves. Link 1 - http://answall.com/questions/130792/dif%C3%A7a-entre-array-de-char-and-char pointer , Link 2 - http://answall.com/questions/116333/ponteiro-de-char-ou-array-de-char .
– pmargreff