Basically what I’m trying to achieve here is having global variable with array of pointers to struct which size isn’t known at compile time — in my example below it’s my_struct **tab. In the final version I want to call a JNI method which will initialize my array of pointers and I want to keep them for some other methods usage.
Unfortunately I’m not a C programmer and I really struggle with this problem. Below I show what I tried to do; obviously, it’s not working. Any constructive feedback would be really helpful.
(Sorry for missunderstanding with includes it’s supposed to be a C code )
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int tag;
} my_struct;
my_struct **tab;
void * get_pointer_to_struct() {
my_struct * s;
/* allocate memory */
if ((s = (my_struct *) malloc(sizeof (my_struct))) == NULL) {
return NULL;
}
return s;
}
void free_structures(int j) {
for (int a; a < j; a++) {
my_struct *s;
s = (my_struct *) tab[a];
/* free memory */
free(s);
tab[a] = NULL;
}
}
void init_pointers_array(int j) {
my_struct * temp_arr[j];
for (int i = 0; i < j; i++) {
temp_arr[i] = (my_struct *) get_pointer_to_struct();
temp_arr[i]->tag = i;
}
tab = temp_arr;
}
int main() {
//initialization
init_pointers_array(10);
//usage
for (int a = 0; a < 10; a++) {
if (tab[a]) {
my_struct * str_tmp = tab[a];
printf("Integer that you have entered is %d\n", str_tmp->tag);
}
}
//free mem
free_structures(10);
return 0;
}
then
is wrong. (Not only the placement of the
*qualifier is horrible and there are superfluous casts that severely decrease code readibility, but)temp_arrayis a local auto array, so it will be deallocated when the function returns. Doing anything with its address afterwards results in undefined behavior. You may want tomalloc()ate some memory for the struct instead (the casts are only there in order the code to be usable in C++. In C, it’s strongly discouraged to make redundant typecasts):And for freeing it: