Home > Back-end >  How do I assign the value of a subarray in C?
How do I assign the value of a subarray in C?

Time:11-22

I've initialised the following array to store moves in a tic-tac-toe game (there can be up to 100 moves (10x10 grid). Each subarray needs to store the row and column of the move, as well as the symbol being placed there.

char moves[100][3];

I then want to insert the three values into each subarray. I use the variable moveCount for the index into which i want to store the subarray of move data.

moves[moveCount] = {row, col, symbol};

however this is throwing the error "expression must be a modifiable lvalue". How do i go about inserting the subarray of move data into the overall array?

CodePudding user response:

There are two errors in this statement

moves[moveCount] = {row, col, symbol};

The first one is that the expression moves[moveCount] is an array and arrays do not have the assignment operator.

The second one is the list in braces is not an expression.

You need to write

moves[moveCount][0] = row; 
moves[moveCount][1] = col;
moves[moveCount][2] = symbol;

Instead of defining the two dimensional array consider a definition of a one-dimensioanl array of objects of a structure type that will contain three data members row, col and symbol.

CodePudding user response:

I'm not sure how to do that on one line but this worked for me:

    char moves[10][3];

    moves[0][0] = 'a';
    moves[0][1] = 'b'; 
    moves[0][2] = 'c';

So if is it acceptable for you to assign the values one by one, that would be an option.

What I also found here is that you can create an additional array and initialise it with your values, then copy it to there you need it.

char moves[10][3];
char values[3] = {'1', '2', '3'};
memcpy(moves[0], values, sizeof(values));

CodePudding user response:

As Vlad said, if you're using braces you need to fill in all values or initialize it with one value like this:

int moves[2][3] = {{row, col, symbol}, {row, col, symbol}};

or

int moves[2][3] = { 0 };

CodePudding user response:

In C you cannot assign values to an array but only to separate array members.

But I doubt that an array is the proper data type for you. You want to store 3 values with different meaning. That would call for a struct instead of an array:

typedef struct {
char row;
char col;
char symbol;
} move_t;

move_t moves[100];

Then you can use a compound literal to assign new values to each element:

moves[movecount]=(move_t){row, col, symbol};
  • Related