So I want to have an array whose size is not known initially (to be taken from the user from command line) but I want to have it globally accessible(outside main).
So here is what I do:
//.h file declaration
typedef struct res
{
int popultaion[NB_TYPE];
int alive;
int birthat[NB_TYPE];
}res_t;
//.c file
res_t* res_first = NULL;
int main(int argc, char* argv[])
{
int no_of_mutants = atoi(argv[1]);
int i,j = 0;
srand(time()NULL);
res_t* tem= res_first;
for(i = 0; i < no_of_mutants; i++)
{
for(j = 0; i < NB_TYPE; i++)
{
tem->popultaion[j] = rand();
}
tem++
}
//...other code
}
I get a segmentation fault., When I debug using gdb, it seems like it is here it gets the SIGSEGV.
tem->popultaion[j] = rand();
I have two questions:
- Is this form of trying to construct an array using adding pointer valid? I am getting segfault in the first run though when the address should technically be valid.
- Is the way of accessing a an array member from a struct valid? (Kind of sure it is but just want to make sure)?
P.S. I am aware of malloc and just could achieve the same thing using malloc but I want to know if this is what giving me problem before going to change everywhere else in the code and if so why?
Why should it? It’s
NULL, so your code invokes undefined behavior. What you have to do is allocate memory for it when the user entered the number of items in the array.and of course, free it after use: