Insty1956
Insty1956

Reputation: 3

Allocate a dynamic 2d-array by passing it to another function by reference

This question builds off of two previously asked questions: C++ Passing a dynamicly allocated 2D array by reference & C - Pass by reference multidimensional array with known size

I was trying to allocate memory for a 2d-Array using the answers of these previous questions, but the memory never been allocated and I receive a BAD_ACCESS error every time a try to access the array!

This is what I have:

const int rows = 10;
const int columns = 5;

void allocate_memory(char *** maze); //prototype

int main(int argc, char ** argv) {
  char ** arr;
  allocate_memory(&arr) //pass by reference to allocate memory
  return 0;
}

void allocate_memory(char *** maze) {
  int i;
  maze =  malloc(sizeof(char *) * rows);
  for (i = 0; i < rows; ++i)
      maze[i] = malloc(sizeof(char) * columns);
}

Upvotes: 0

Views: 429

Answers (1)

haccks
haccks

Reputation: 106012

First you should note that there is no pass by reference in C, only pass by value.

Now, you need to allocate memory for maze[0] (or *maze)

*maze =  malloc(sizeof(char *) * rows);  

and then

for (i = 0; i < rows; ++i)
  (*maze)[i] = malloc(sizeof(char) * columns);

Upvotes: 3

Related Questions