How to give 'value' to a char variable?

Asked

Viewed 451 times

-4

I have a question about how I can give value to the char variable without the scanf command, for example: I have a variable called name and I want to say that it is worth maria. how do I do that? I’ve tried everything and I can’t :p

  • Choose an answer that answered your question, it helps the community a lot.

2 answers

2

Well, put "maria" in a variable like char it is not possible because this type waits only one character, it is possible to do this in a pointer to a properly allocated area in memory, which can be in the stack as a vector, the easiest but least common in real code. So:

char nome[6] = "maria";

in this case what you are doing is creating an area on the runstack by reserving 6 characters, therefore 5 for the name you want to store the most terminator necessary for all string. And in this location will be placed a value already established 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', '\0' };

If it is in the heap:

char nome = malloc(6);
strcpy(nome, "maria");

I put in the Github for future reference.

1


char str[6]="maria";

Is that? maria has 5 characters, but has to book +1 because of the ' 0', so we reserve 6 of static memory

Browser other questions tagged

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