SOLSD
SOLSD

Reputation: 23

Extra Printing of Chars in 2D Char Array

I'm trying to print out each element of a 2d char arrray in turn using this piece of code:

#include <stdio.h>
#include <stdlib.h> 
char positions[3][3] = {'A', 'B', 'C', 'D', 'E', 'F','G', 'H', 'I'};
    int main(){
        for(int i = 0; i < 3; i++){
            for(int j = 0; j < 3; j++){
                printf("%s \n", &positions[i][j]);
            }
        }
        return 0;
    }

But the output is:

ABCDEFGHI 
BCDEFGHI 
CDEFGHI 
DEFGHI 
EFGHI 
FGHI 
GHI 
HI 
I

Instead of:

A
B
C
D
E
F
G
H
I

And I can't work out how to fix it. I've looked around and haven't been able to find any answers to this specfic issue. Any advice would be great. Thank you.

Upvotes: 2

Views: 102

Answers (2)

The Programming M16A4
The Programming M16A4

Reputation: 397

There were a couple of things you did wrong.

  1. You did not create a proper 2D array. You did create a 2D array, but you formatted it so that it looked like a 1D array (As seen in your code). This does compile however you don't want to be using this style.

  2. You made it print the elements using %s which is meant for strings, not chars, you would use %c for that.

Everything else checks out though! The below code is how you could properly declare a 2D array:

#include <stdio.h>

int main() {
    // The last square bracket shows how many elements each
    // Array can hold
    char positions[3][3] = {
        {'A', 'B', 'C'},
        {'D', 'E', 'F'},
        {'G', 'H', 'I'}
    };

    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            printf("%c\n", positions[i][j]);
}

Upvotes: 2

xddq
xddq

Reputation: 381

Your printf does take %s which forces the char array to be converted to a string starting from the first entry. Try running

printf("%c \n", positions[i][j]);

to print out characters. And see what happens ;)

greetings

Upvotes: 5

Related Questions