I'm not too experienced in C, but I've been recently writing some program in the language to speed it up a little bit (it was originally written in python). I don't really have a problem anymore since I already managed to solve my original problem. However, I would like to know why this solution works.
I have a data structure representing complex numbers defined as
typedef struct _fcomplex { float re, im; } fcomplex;
Then I want to create an array of complex numbers as:
fcomplex M[N];
Here N is a large number (something like ~10^6). Then I initialize the array with zeros in a function that essentially runs through all the indices and sets the values in the array. It's something like:
fcomplex num = {0.0, 0.0};
int i;
for (i=0 ; i < N ; i++) {
M[i] = num;
}
However, when I run the code, it results in a segmentation fault. However, if I use malloc() to allocate space for the array instead as
fcomplex* M = malloc(N*sizeof(fcomplex));
and then do everything as before, the code works fine. Also, for smaller values of N, the code runs fine either way.
As I said, using malloc() already solved the problem, but I would like to know why?