First off, let me begin by saying I KNOW that this question has been answered at some point. It had to have been, but I simply do not know the keywords to find an answer to it.
I am writing a program, and inside of my program I have to create multiple dynamically sized arrays all over the place, and then store them to one grand struct. So if I had to create the same type of dynamically allocated array, I create it in a function (meaning declare it, malloc it, and return it) to my struct field. However, now that I am down the road I think that I made a major flaw. I believe what I did is destroyed by the scope of the function, meaning once the function completes, the original pointer is killed and therefore my struct is pointer to a address that is no longer “mine”. Below is a sample call to the function, hopefully it makes sense without comments.
//Call from main()
current_event->mens_names = create_names_matrix(number_of_couples, 20);
//my "create_names_matrix" function:
char ** create_names_matrix(int num_of_names, int length_of_names){
int i;
char **return_matrix;
return_matrix = malloc(num_of_names * sizeof(char*));
if(return_matrix == NULL){
panic("return_matrix"); //Panic is a function that checks if malloc failed
}
for(i = 0; i < num_of_names; i++){
return_matrix[i] = malloc(length_of_names * sizeof(char));
}
if(return_matrix[i-1] == NULL){
panic("return_matrix"); //Panic is a function that checks if malloc failed
}
return return_matrix;
}
would a solution be to go ahead and declare and dynamically create each field array in the main, and then pass that into each of my “create_xxx_matrix” functions as a parameter to avoid them being killed after the scope of the function is complete?
I know this is a noob question but it has been a while since I worked with pointers & c.
Thanks!
Dynamically allocated pointers are allocated in the heap and not killed by the scope of the function. By scope, the variables allocated in the stack are destroyed once they leave the function.