[英]Initialization of 3D global arrays in C
I have global 3D arrays defined as 我将全局3D数组定义为
double*** arr;
in a file common.c 在文件common.c中
I have the declaration 我有宣言
extern double*** arr;
in a file common.h 在文件common.h中
Now when I am initializing this array dynamically at runtime, I am running into a segmentation fault I executed the code 现在,当我在运行时动态初始化此数组时,遇到了分段错误,我执行了代码
exs =malloc(sizeof(double)*nx*ny*nz);
where nx,ny and nz are known at runtime prior to executing this statement. 其中,执行此语句之前,在运行时已知nx,ny和nz。
But when i try to initialize this array as 但是当我尝试初始化此数组为
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++)
arr[i][j][k]=0.0e0;
I get a segfault. 我遇到了段错误。
What am I doing wrong ? 我究竟做错了什么 ?
You need to allocate all dimensions: 您需要分配所有尺寸:
arr = malloc(sizeof(*arr) * nx);
for (int i = 0; i < nx; i++)
{
arr[i] = malloc(sizeof(**arr) * ny);
for (int j = 0; j < ny; j++)
{
arr[i][j] = malloc(sizeof(***arr) * nz);
for (int k = 0; k < nz; k++)
{
arr[i][j][k] = 0.0;
}
}
}
And of course don't forget to free all the data you allocated. 当然,不要忘记释放分配的所有数据。
First of all, arrays are not pointers . 首先, 数组不是指针 。
Second, let me show you another solution which tries to avoid memory fragmentation and uses one single call to the malloc()
function (which is expensive): 其次,让我向您展示另一种解决方案,该解决方案尝试避免内存碎片,并使用单个调用
malloc()
函数(这很昂贵):
double (*arr)[ny][nz] = malloc(sizeof(*arr) * nx);
After this, you can use arr
as an array of dimensions nx * ny * nz
. 之后,您可以将
arr
用作尺寸为nx * ny * nz
的数组。
And if you want this to be used at file scope: declare it as void *
, allocate memory for nx * ny * nz
elements, then assign it to a pointer-to-array when used for convenience: 如果要在文件范围内使用此方法:请将其声明为
void *
,为nx * ny * nz
元素分配内存,然后为方便起见将其分配给数组指针:
// common.h
extern void *ptr;
// common.c
ptr = malloc(sizeof(double) * nx * ny * nz);
// foo.c
double (*arr)[ny][nz] = ptr;
But if you need such a hack... you should be thinking about what you have done wrong. 但是,如果您需要这样的技巧……您应该考虑自己做错了什么。 Well, in this case, you've done wrong one thing: you are using a global variable.
好吧,在这种情况下,您做错了一件事情:您正在使用全局变量。 Don't use it.
不要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.