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.

4
  • 1
    Use the correct function signature. long[][] and long** differ. Commented Oct 8, 2014 at 18:55
  • How does that even compile? Commented Oct 8, 2014 at 18:57
  • 1
    possible duplicate of Pass multiple-dimensional array to a function in C Commented Oct 8, 2014 at 19:01
  • Thanks everyone for your response. @RSahu Thanks for that post. It was very helpful. Commented Oct 8, 2014 at 20:50

1 Answer 1

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.

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

Comments

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.