1

I'm trying to create a grid of characters, and for this example am using a 3by 3 grid. I am using two for loops to assign from a separate one dimensional array of characters, but the final value in each row is always equal to the first value of the next, but can't understand why. Is something wrong with my calculation of row and col?

char text[8] = "abcdefghi";
char grid[2][2];

int i,j;
for(i=0; i<=8; i++)
{
    char c = text[i];
    int row = i/3;
    int col = i%3;
    printf("%c   row=%d col=%d i=%d\n", c, row, col, i);
    grid[row][col] = c;
}

printf("------\n");

for(i=0; i<3; i++)
{
    for(j=0; j<3; j++)
    {
        printf("%c   row=%d col=%d \n", grid[i][j], i, j);
    }
}
1
  • Thats not a 3x3 array. And enable your compiler warnings. How many characters, including the terminator, are in "abcdefghi"? Commented Sep 13, 2013 at 21:11

2 Answers 2

2

change these two declarations

char text[8] = "abcdefghi"; //you require size of 10  
//9 bytes to store 9 characters and extra one is to store null character

char grid[2][2];  here you need to declare 3 by 3    
// array[2][2] can able to store four characters only  
// array[3][3] can store 9 characters  

Like this

char text[10] = "abcdefghi"; //you require size of 10
char grid[3][3];  here you need to declare 3 by 3  
Sign up to request clarification or add additional context in comments.

3 Comments

@BenElgar Don't worry , these are common mistakes done at the stage of beggining. with out making mistakes you can't learn...cheer up.
Better yet, do char text[] = "abcdefghi"; & save yourself from the trouble of miscounting :)
@KingsIndian yes. i forgot add that in answer.but already suggested another answer.
2

You have an error on the first line

char text[8] = "abcdefghi"; 

You declare an array of size 8 but you want to initialize it with 10 characters. Do either this or this:

char text[10] = "abcdefghi"; 

char text[] = "abcdefghi"; 

Similar error is with char grid[2][2]; where you have 2 by 2 grid instead of 3 by 3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.