Home > Net >  Initialize a matrix with constant string in c
Initialize a matrix with constant string in c

Time:10-12

I'm trying to learn c by doing some easy stuff that I find on the internet. I'm trying to initialize this matrix with a constant string (i.e. "@"), in order to fill it later. Hence, the output is not what I'm expecting. Can you please tell me what I'm doing wrong? Can you give me some advice on how to better initialize the matrix with a constant string?

#include <iostream>
#include <string>
using namespace std;
char* Board[3][3];
char* PLAYER = "X";
char* COMPUTER = "O";

void displayBoard() {
    printf(" %c | %c | %c ", Board[0][0], Board[0][1], Board[0][2]);
    printf("\n---|---|---\n", Board[0][0], Board[0][1], Board[0][2]);
    printf(" %c | %c | %c ", Board[1][0], Board[1][1], Board[1][2]);
    printf("\n---|---|---\n", Board[0][0], Board[0][1], Board[0][2]);
    printf(" %c | %c | %c ", Board[2][0], Board[2][1], Board[2][2]);
    printf("\n---|---|---\n", Board[0][0], Board[0][1], Board[0][2]);
}

void FillBoard() {
    char* initialValue = "@";
    for (int i=0; i<3; i  ) {
        for (int j=0; j<3; j  ) {
            Board[i][j] = initialValue;
        }
    }
}

int main () {
    FillBoard();
    displayBoard();
}

Output:

 f | f | f
---|---|---
 f | f | f
---|---|---
 f | f | f
---|---|---

CodePudding user response:

There are many isssues. Explanation in comments.

But as one of the a comments above says: get a good C book. BTW your code is rather C code than C code.

#include <iostream>
#include <string>
using namespace std;
char Board[3][3];
const char PLAYER = 'X';    // you don't need a pointer here, you need a char here
const char COMPUTER = 'O';  // same as above

void displayBoard() {
  printf(" %c | %c | %c ", Board[0][0], Board[0][1], Board[0][2]);
  printf("\n---|---|---\n");   // removed the extra arguments
  printf(" %c | %c | %c ", Board[1][0], Board[1][1], Board[1][2]);
  printf("\n---|---|---\n");   // removed the extra arguments
  printf(" %c | %c | %c ", Board[2][0], Board[2][1], Board[2][2]);
  printf("\n---|---|---\n");   // removed the extra arguments
}

void FillBoard() {
  const char initialValue = '@';  // you don't need a pointer here, you need a char here
  for (int i = 0; i < 3; i  ) {
    for (int j = 0; j < 3; j  ) {
      Board[i][j] = initialValue;
    }
  }
}

int main() {
  FillBoard();
  displayBoard();
}

CodePudding user response:

For one, you have made a critical mistake in your above code example. Don't ever write(in C atleast):

char* initialValue = "@";    //incorrect

Instead the correct way to write the above statement is:

const char* initialValue = "@";    //correct

This is because the use of string literal without the const keyword is forbidden. See here

Also you could just use/create a matrix of char instead of char* as you did in your example and similarly for other uses of char*. Jabberwocky 's answer shows this.

  • Related