Samhan Salahuddin
Samhan Salahuddin

Reputation: 2170

Same Code Giving Different Output in C

I am stumped by this. I am pasting the program below.

void printGrid(int n,char grid[n][n]){
    for(int i = 0; i<n ; i ++) {
        printf("\n%s",grid[i]);
    }
}

int main() {    
    char grid[6][6]= {"-----","-----","-----","-----","-----"};

    printGrid(5, grid);

    for(int i = 0; i<5 ; i ++) {
        printf("\n%s",grid[i]);
    }
    return 0;
}

Output:

-----
-
--
---
-----
-----
-----
-----
-----

Why does the same for loop produce different output outside and inside the function printGrid?

Upvotes: 0

Views: 272

Answers (1)

FatalError
FatalError

Reputation: 54551

You re using a VLA but the size does not match the dimensions of the array you passed in. When you have an array:

char a[m][n];

The char at a[x][y] is found essentially by a + x*m + y. Moreover, the layout of the array you made in memory looks like this:

-----\0-----\0-----\0-----\0-----\0-----\0

But since your first dimension is 5 instead of 6, when you index each row you are hitting it like this:

-----\0-----\0-----\0-----\0-----\0-----\0
^     |    |     |     |     |     |
      ^    |     |     |     |     |
           ^     |     |     |     |
                 ^     |     |     |
                       ^     |     |
                             ^     |
                                   ^

(your loop doesn't actually print the last two). If you instead call it like:

printGrid(6, grid);

you will see the output is more what you expect because the strides line up. The other loop should probably be using 6 as well.

Upvotes: 5

Related Questions