Why does a string assignment in C not work?

2

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 an error is occurring from Segmentation Failure When I compile test.c|11|warning: assignment makes integer from pointer without a cast| appears

and when I run it appears Segmentation Fault

Now when I point out that my variable name and pointer variable works normally it goes 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 running I get the following return

'Safari' '9'

My problem is related to the type char for this question of my question Is there any problem in assigning a value to a pointer? I know this method is not advisable but it was the only mode that worked so far, anyone knows why it is happening Segmentation Fault in first example?

    
asked by anonymous 23.06.2016 / 04:08

1 answer

4

The main mistake is to think that the assignment operator works for strings . You do not need to call the function that copies the characters you want to ( strcpy() ).

There is still a problem missing a byte for the terminator character %code% . Every string in C needs one more byte. C is a crude language, the programmer has to worry about everything.

#include <stdio.h>
#include <string.h>

typedef struct Animal {
    char nome[6]; //o tamanho tem que ser 6 para acomodar o terminador
    int idade;
} Cachorro;

int main() {
    Cachorro dog;
    dog.idade = 9;
    strcpy(dog.nome, "Salfr"); //é a forma correta pra copiar uma string para uma variável
    printf("'%s' '%d'", dog.nome, dog.idade);
    return 0;
}

See working on ideone and on CodingGround .

The version with pointer works, as long as you do not want to ever touch the text. It is causing the structure to point to a region of memory "belonging to the code" and is protected. The normal thing is not to do this. This may work by coincidence. There it is a worse solution because it does not allocate memory needed to support the text object. The text could only be manipulated after this allocation. Even if it did it would still have the problem of copying that is not being done.

I made cosmetic changes, but important. Stay tuned.

Running is one thing, being right is another. I advise learning the right thing and not trusting what worked. It may have been just a coincidence.

    
23.06.2016 / 04:54