0

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);
}
5
  • 1
    Small point: why are you using 10 for the malloc call when you have defined rows which you use immediately after? Commented Apr 7, 2016 at 8:51
  • 1
    Please don't try to be a three-star programmer. Other than that technically C doesn't have "pass by reference", you can only emulate it. Commented Apr 7, 2016 at 8:52
  • Was a typo, I already fixed it. Thanks for notifying Commented Apr 7, 2016 at 8:52
  • 1
    As for your problem, in the function you have a pointer to the pointer to the pointer. The first indirection is because you passed a pointer to the variable, but that's only local inside your function. Have you ever wondered about the dereference operator * sometimes, and when to use it? Now might be a good idea to read up about it. Commented Apr 7, 2016 at 8:53
  • Note that maze = malloc(sizeof(char *) * 10); will only change the local copy passed to it. It won't affect the pointer you passed, which remains uninitialised. Commented Apr 7, 2016 at 8:53

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

6 Comments

can I use *maze instead of maze[0]? is it the same?
@Insty1956 yes, remember to write (*maze) though when using [] after
@Insty1956; Yes. You can.
*maze[i] = malloc(sizeof(char) * columns); should be (*maze)[i] = malloc(sizeof(char) * columns);. Updated the answer.
Maybe you can also change the signature to char **allocate_memory(int rows, int columns).
|

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.