1

I need to allocate a char** array that points to a 2 dimensions chars array.

Eventually, I want to point to a "cell" like players[playerNum][Row][Col]. This is what I wrote so far, but it fails. It is hard to understand the logic behind it, so if you can explain me whats wrong it will be great.

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

int main(int argc, char *argv[]) {
        int numOfPlayers;
        int i,j;
        char** players = (char **)malloc(sizeof(char**)*numOfPlayers); // players array
        for (i=0 ; i<numOfPlayers ; i++){
                players[i] = (char *)malloc(sizeof(char*)*10); // each player 1st D array
        }
        for (i=0 ; i<10 ; i++){
                for (j=0 ; j<10 ; j++){
                        players[i][j] = (char *)malloc(sizeof(char*)*10);      
                }
        }
        return 0;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
user2216190
  • 784
  • 5
  • 10
  • 25

1 Answers1

4

Allocation in your code is wrong!

Do like this:

    char** players = malloc(sizeof(char*) * numOfPlayers); 
                                       ^ remove one *  
    for (i=0 ; i<numOfPlayers ; i++){
            players[i] = malloc(sizeof(char)* 10); // each player 1st D array
                                    //    ^ remove * it should be char
    }

note: sizeof(char) != sizeof(char*).
You don't need second nested for loop too. (just above code is fine) Also avoid casting return value from malloc/calloc in C

Note A mistake in your code is that numOfPlayers is not initialized (you are trying with garbage value).

Comment:

But then, i only have 2D array. i need an array that each cell of him points to a 2D array like so... you misunderstood my question

Read if you wants - a matrix of String or/ 3D char array

To allocate a matrix like: players[playerNum][Row][Col]

char ***players;
players = calloc(playerNum, sizeof(char**)); 
for(z = 0; z < playerNum; z++) { 
    players[z] = calloc(Row, sizeof(char*));
    for(r = 0; r < Row; r++) {
        players[z][r] = calloc(Col, sizeof(char));
    }
}

Edit If you wants to allocate continues memory for data, then you can use following technique. It will also be preferable because it makes less call of malloc function.

char *players_data,  // pointer to char 
     ***players; // pointer to 2D char array
players_data = calloc(playerNum * Row * Col, sizeof(char)); //1 memory for elements 
players = calloc(playerNum, sizeof(char **)); //2 memory for addresses of 2D matrices 
for(i = 0; i < playerNum; i++){
  players[i] = calloc(Row, sizeof(char*)); //3 memory for data cols
  for(r = 0; r < Row; r++){ //4  Distributed memory among rows
     players[i][r] = players_data + (i * Row * Col) + (r * Col);
  }
}

A good reference to learn: Dynamic Three Dimensional Arrays in C\C++

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208