简体   繁体   中英

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.

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

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM