How to give value to a char variable?

-4

I have a question about how I can give value to the variable char without being by the scanf command, for example: I have a variable named name and I mean that it is worth maria. how do I do that? I tried everything and I can not: p

    
asked by anonymous 14.08.2018 / 01:17

2 answers

1
char str[6]="maria";

Is that it? maria has 5 characters, but you have to book +1 because of '\ 0', so we reserved 6 static memory

    
14.08.2018 / 01:20
2
Well, putting "maria" in a variable of type char does not give because this type expects only one character, it is possible to do this in a pointer to an area properly allocated in memory, which can be in stack as a vector, the easiest but less common in real code. So:

char nome[6] = "maria";

In this case what you are doing is creating an area in the execution stack by reserving 6 characters, thus 5 for the name you want to store plus the terminator required for every string . And in this place will be placed an already established value in the static area of the application memory.

So this is the simplest way to do it without extra interventions.

Another weird syntax that works would be:

char nome[6] = { 'm', 'a', 'r', 'i', 'a', '
char nome = malloc(6);
strcpy(nome, "maria");
' };

If it is in heap :

char nome[6] = "maria";
    
14.08.2018 / 01:21