1

Getting segmentation fault while accessing the data from a static global array from another file; the pointer was passed as a function argument. The memory address shows the same from both file.

In file1.c

static long long T[12][16];
...
/* inside some function*/
  printf(" %p \n", T); // Check the address
  func_access_static(T);
...

In file2.c

void func_access_static(long long** t)
{
  printf(" %p \n", t); // shows the same address
  printf(" %lld \n", t[0][0]); // gives segmentation fault
}

Am I trying to do something that can't be done? Any suggestion is appreciated.

Rakib
  • 791
  • 8
  • 19

1 Answers1

2

** is not the same thing than an array.

Declare your function

void func_access_static(long long t[][16])

or

void func_access_static(long long (*t)[16])

This is what a 2 dimensional array int t[2][3] looks like in memory

                              t
              t[0]                          t[1]
+---------+---------+---------+---------+---------+---------+
| t[0][0] | t[0][1] | t[0][2] | t[1][0] | t[1][1] | t[1][2] |
+---------+---------+---------+---------+---------+---------+
     Contiguous memory cells  of int type

This is what a pointer on pointer int ** looks like in memory

  pointer           pointer   pointer
+---------+       +---------+---------+       
|   p     |  -->  | p[0]    |  p[1]   |
+---------+       +---------+---------+      
                       |         |            Somewhere in memory
                       |         |           +---------+---------+---------+
                       |         \---------->| p[1][0] | p[1][1] | p[1][2] |
                       |                     +---------+---------+---------+
                       |
                       |                      Somewhere else in memory
                       |                     +---------+---------+---------+
                       \-------------------->| p[0][0] | p[0][1] | p[0][2] |
                                             +---------+---------+---------+

To access the content it's the same syntax but the operation is quite different.

Patrick Schlüter
  • 11,394
  • 1
  • 43
  • 48