-
Queer 2D-Array
I bet you were missing me,
I have a problem with my 2D array as it seems to have random values in certain places...
Code:
//definition:
char board[3][3];
Then when I output certain parts of it to where they should go I get random characters instead of blankness.
:rolleyes: :rolleyes: :rolleyes: :rolleyes: :rolleyes: :rolleyes:
-
Provide an initialization if this definition is in block scope, otherwise you are pretty much guaranteed garbage values.
-
Ok thanks, how exactly do I initialize it to 0?
-
Code:
char board[3][3] = {0};
-
ah right thanks I wasn't sure how to do it without defining each part.
-
As a side note to what Dave already provided you, it is important you understand something...
Had you defined that array outside any function (and main() is a function), the array would have been initialized for you. Variables of the local type (variables defined inside a function) are not initialized automatically. Variables of the global type, are.
Also...
An array can be initialized by providing only a value for the first element, when defining it. That is what Dave provided. But (and this is a big but) never forget that what happens here is that the rest of the array elements are initialized according to the rules of their type, and not to the value you provided. On the case of chars, it means they are initialized to 0.
Type this...
Code:
char board[3][3] = {7, 2};
And then check your array elements. You will see that, just like before you no longer have garbage values. But you will also realize that the first element of your array contains 7, the second contains 2, and all others contain 0.
-
Thank you very much, I think you have just solved a problem, cheers.
-
How do I clear all the elements of my array after it has been defined?
-
If by clear you mean resetting their values to 0, you can traverse the array elments in a for or while loop and set each element to 0.