Reputation: 15
Im trying to make a tictactoe game in C and decided to use a 2d char array to create the gameboard. A nested for loop is probably best suited for this but I cant quite understand how I should adress individual strings in an array
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char board [5][8]={" | | ","--+--+--"," | | ","--+--+--"," | | "};
printf("%s",board[1][0]);
}
Upvotes: 1
Views: 64
Reputation: 67805
Because your array is to short to keep the C string (which requires one element more to accommodate the null character) you cant use any C functions which operate on C strings.
How to print this array?:
int main(void) {
char board [5][8]={" | | ","--+--+--"," | | ","--+--+--"," | | "};
for(size_t row = 0; row < sizeof(board) / sizeof(board[0]); row++)
{
for(size_t col = 0; col < sizeof(board[0])/ sizeof(board[0][0]); col++)
printf("%c", board[row][col]);
printf("\n");
}
}
https://godbolt.org/z/4qo4rx6oY
But if you change the size of the array you can use string functions.
int main(void) {
char board [5][9]={" | | ","--+--+--"," | | ","--+--+--"," | | "};
for(size_t row = 0; row < sizeof(board) / sizeof(board[0]); row++)
printf("%s\n", board[row]);
}
Upvotes: 1