1

How can i define an array in C language for strings without using pointers ? I am trying to create a chessboard.

#include <stdio.h>
#include <string.h>

int main(void){

char board[8][8] = {{ "R1 ", "N1 ", "B1 ", "QU ", "KI ", "B2 ", "N2 ", "R2 "},

                   { "P1 ", "P2 ", "P3 ", "P4 ", "P5 ", "P6 ", "P7 ", "P8 "},
                   { "","","","","","","",""},
                   { "","","","","","","",""},
                   { "","","","","","","",""},
                   { "","","","","","","",""},
                   { "p1 ", "p2 ", "p3 ", "p4 ", "p5 ", "p6 ", "p7 ", "p8" },
                   {"r1 ", "n1 ", "b1 ", "qu ", "ki ", "b2 ", "n2 ", "r2 "}};

}

I get an error " excess elements in char array initializer ". What should i do ? I am not allowed to using pointer.

4
  • 2
    You are placing strings and not chars as elements in your char array. Commented Dec 1, 2013 at 11:09
  • strings in C are char arrays. you can't get a string with no pointers. Commented Dec 1, 2013 at 11:10
  • 1
    Your initialiser it an initialiser for char * board[8][8]. It carries 8X8 "strings". char[8][8] expects 8X8 chars. Commented Dec 1, 2013 at 11:11
  • This is an 8x8 array of char: char board[8][8]. You want an 8x8 array of strings: char *board[8][8]. Commented Dec 1, 2013 at 11:16

1 Answer 1

5

You're defining a 2D array consisting of strings. Since strings themselves are arrays in C/C++, you're essentially creating a 3D array.

There are multiple ways to fix this:

  • You can use char *board[8][8] to define an 8x8 array of pointers to the strings.
  • You can use char board[8][8][4] to add the missing dimension (this uses the same memory no matter how long single entries are; each entry may have up to 3 characters plus 1 terminator).

As a side note, you should use the const keyword, as you typically won't want to modify the string contents.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.