Help me Thor game (Strings)

How do i initialize a string that Ive declared in the main?

I declare a string in the main e.g. char command[3];

initialize it in the game loop, e.g. command[3] = “NW”;
When i print it inside the loop, it shows me “NW”, which is what I expect,

However, when i print this value outside the loop it goes to some gibberish?
It gives me this funny value ���

Plz help what am i doing wrong??

The line:
command[3] = “NW”;
is not legal in C.
Probably you wrote this line inside the loop:
char command[3] = “NW”;
In this way you created another string inside the loop, so it will only works inside it.
The correct line inside the loop is:
strcpy( command, “NW” );
This line above copies “NW” to command

2 Likes

That’s why u should always initialize a variable when u declare it. Even if it is of no use for ur code (algorithm) it will help u to control it and what values it holds…

So when u just declare it u are allocating the memory for it. But if u don’t specify a value for ur variable to hold it will have what ever was on that space of memory.
Then u try to assign a value with illegal statement: command[3] = “NW”; it shouldn’t even compile but most likely its just ignored.
And finaly when u try to print it u get the best out of what ever its in the allocated memory…

When i have to initialize variables like this (in a place i don’t want or need to) i give them a value that my algorithm doesn’t use. Like if i only use none negative ints i set a int variable to -1. So when i’m debugging if at any point my variable has a value of -1 i know its because it hasn’t been altered since i declare it.

In ur case u may just empty declare it like:
command[3] = “”;

witch is the same of 3 null chars ‘/0’ : command[3] = {0, 0, 0,}
“zero” is the ASCII value of NULL so 0 = ‘/0’ in this :slight_smile: