0

I'm getting this error on line #4 which says 'invalid initializer'. I know what the error means, but I can't work out why i'm getting the error. I've tried all sorts of combinations of pointers and values, but it doesn't seem to want to work. Any help / feedback for the code would be greatly appreciated.

Note: I plan to have a 2D array for the chessboard, which mean 64 ints of memory malloc'd. The printf is there to keep the compiler happy and show me whether at [4][2] there is a '0'.

int *newBoard();    
int main(int argc, char *argv[]) {

   int *chessBoard[7][7] = *newBoard();
   printf ("%d", chessBoard[4][2]);

   return EXIT_SUCCESS;
}

int *newBoard() {

   int counter = 0;
   int *blankBoard = malloc(sizeof((int) * TOTALSPACES));

   while (counter < TOTALSPACES) {
      blankBoard[counter] = VACANT;
      counter++;
   }

   return blankBoard;
}

3 Answers 3

1

newBoard returns an array of TOTALSPACES ints. int *chessBoard[7][7] = *newBoard(); LHS is a 7x7 array of int pointers (not ints). RHS is what, the contents of of an int pointer returned by the call? (what do you think the * infront of the call to newBoard() is doing?

Either int *newBoard = newBoard(); (to use heap memory) or int newBoard[7][7]; (to use stack memory) would work. You are trying to do half of each!

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

Comments

0

int *chessBoard[7][7] stands for an 2D array(7*7), each element type is int*; but *newBoard() stand for an int element.

Comments

0
#include <stdio.h>
#include <stdlib.h>

#define TOTALSPACES 8*8
#define VACANT '0'

void *newBoard();

int main(int argc, char *argv[]) {

    int (*chessBoard)[8][8] = newBoard();
    printf ("%d", (*chessBoard)[4][2]);//48 : '0'

    return EXIT_SUCCESS;
}

void *newBoard() {
    int *blankBoard = malloc(sizeof(int) * TOTALSPACES);
    int counter = 0;

    while (counter < TOTALSPACES)
        blankBoard[counter++] = VACANT;

    return blankBoard;
}

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.