0

I have a two dimensional array of pointers declared in main as

char* data[3][8] 

which I passed into a function

void func(char*** data) 

When I did printf("%p\n", data[0]); in main and in the function I got different outputs 0x7ffeabc27640 in main and (nil) in the function. Albeit printing just data outputs the same address with that from inside the main. Why can't I access the array in the function.

2
  • 2
    Enable warnings and try again. Commented Aug 4, 2015 at 8:09
  • 2
    The 2D array of pointers you are trying to pass is not a char ***. Commented Aug 4, 2015 at 8:12

2 Answers 2

5

If you enable some warnings (which you should always do), you'll get :

main.cpp: In function 'main': main.cpp:6:10: warning: passing argument 1 of 'func' from incompatible pointer type func(data); ^ main.cpp:2:6: note: expected 'char ***' but argument is of type 'char * (*)[8]' void func(char*** data) { (void)data; } ^ 

Which tells you exactly what's wrong, namely that an array is not a pointer. Dereferencing a pointer that has been converted to the wrong type is undefined behaviour, so you can get anything back.

Have your function take in a char *(*)[8] if you want to give it a char *(*)[8] :

void func(char *(*data)[8]); 

Or, if you want to emphasize that data should point to the first element of an array :

void func(char *data[][8]); 

The two syntaxes are perfectly equivalent.

Note : the file is named main.cpp but is indeed compiled in C mode.

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

3 Comments

So just to complete the answer. Your function prototype should either be foo(char* bar[3][8]); or foo(char* bar[][8]);. If you choose to use the second one, you could also pass the number of elements (of your array's first dimension) as second parameter of the function as @Neil suggested.
@kimimsc foo(char* bar[][8]) is sugar for foo(char *(*bar)[8]), though. I'm keeping this answer as a minimal solution to the actual error, Neil has dug up a great demonstration and there's no point repeating it.
Yea I know that but am not sure the OP does since (s)he doesn't seem to know the difference between (char *** and char* [n][m]).
0

Passing 2D arrays to a function -

This will help you read-up and better understand how to do this...

http://www.geeksforgeeks.org/pass-2d-array-parameter-c/

The below is a snippet from the web-page - showing one example of how to do this.

#include <stdio.h> const int n = 3; void print(int arr[][n], int m) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", arr[i][j]); } int main() { int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr, 3); return 0; } Output: 1 2 3 4 5 6 7 8 9 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.