【发布时间】:2016-07-18 18:34:09
【问题描述】:
我正在尝试在C上写一个数组(2x20000)。测试代码是:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double test( int smod )
{
//
// test subroutine
//
double vect_fma[2][20000];
int i;
// write on file //
FILE *f = fopen("file.txt", "w");
///////////////////
for( i = 1; i < 20001; i = i + 1 ){
// allocate the vector for the fma analysis
vect_fma[1][i] = i*smod;
vect_fma[2][i] = i*smod;
if ( i%smod == 0 )
fprintf(f, "%f %f %f \n", 1.0*i, vect_fma[1][i],vect_fma[2][i] );
}
fclose(f);
return 0;
}
int smod;
void main()
{
smod = 10; // every 10 print the output
test(smod); // call the function
}
我用gcc test.c -lm -o test 编译了代码,我收到了Segmentation fault (core dumped)。
就我是 C 的新手而言,我知道“the compiler tries to store it on the stack”和解决方案可能是链接页面中提供的解决方案....但是如果比较,该解决方案看起来很奇怪(而且理解起来很复杂)使用更简单的数组 real(8), dimension(n:m) :: vect_fma 的 fortran 声明,我可以将其放入子例程或函数中而不会出现问题。
也许我在代码中写的声明类似于 fortran real(8), dimension(n,m),allocatable :: vect_fma one ?
所以问题是,在 C 中是否存在一种更简单的方法来在函数内声明数组? 非常感谢大家。
【问题讨论】:
-
对于堆栈来说可能太大 - 请改用堆
-
@EdHeal 类似
2d_array = (int *)malloc(sizeof(int)*N*M);? -
您是否在编译期间(这是您的答案所暗示的)或执行期间收到分段错误?
-
C 数组总是基于 0 的索引,而不是基于 1 的索引。
vect_fma[2]在数组边界之外,vect_fma[1][i]在i == 20000时也是如此。 -
@CorbinMc 在执行期间