【问题标题】:Accessing static global array from another file via function argument通过函数参数从另一个文件访问静态全局数组
【发布时间】:2014-12-03 12:44:05
【问题描述】:

从另一个文件访问静态全局数组中的数据时出现分段错误;指针作为函数参数传递。两个文件显示的内存地址相同。

在文件 1.c 中

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

在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
}

我是否正在尝试做一些无法做到的事情?任何建议表示赞赏。

【问题讨论】:

标签: c arrays static segmentation-fault arguments


【解决方案1】:

** 与数组不同。

声明你的函数

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

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

这是二维数组int t[2][3]在内存中的样子

                              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

这是指针int **上的指针在内存中的样子

  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] |
                                             +---------+---------+---------+

访问内容的语法相同,但操作完全不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 2012-08-23
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    相关资源
    最近更新 更多