基本上我要在这里实现的是使用带有结构指针数组的全局变量,在编译时不知道这个大小 - 在我的例子下面是my_struct **tab
。在最终版本中,我想调用一个JNI方法,该方法将初始化我的指针数组,我想保留它们用于其他一些方法。
不幸的是,我不是C程序员,我真的很难解决这个问题。下面我展示了我尝试做的事情;显然,它不起作用。任何建设性的反馈都会非常有帮助。
(抱歉错误,包括它应该是C代码)
#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;
}
答案 0 :(得分:3)
这段代码是如此难以理解我很惊讶任何人都不敢阅读它。遵循这些准则,您的所有问题都将得到解决:
答案 1 :(得分:1)
my_struct * temp_arr[j];
然后
tab = temp_arr;
是错误。(不仅*
限定符的位置太可怕而且有多余的强制转换会严重降低代码的可读性,但是)temp_array
是 local auto array,所以当函数返回时它将被释放。之后对其地址执行任何操作都会导致未定义的行为。您可能希望malloc()
为结构替换一些内存(转换只是为了使代码可以在C ++中使用。在C中,强烈建议不要进行冗余的类型转换):
my_struct **tab;
tab = (my_struct **)malloc(sizeof(tab[0]) * number_of_structs);
int i;
for (i = 0; i < number_of_structs; i++) {
tab[i] = (my_struct *)malloc(sizeof(tab[0][0]));
}
为了解放它:
int i;
for (i = 0; i < number_of_structs; i++) {
free(tab[i]);
}
free(tab);
答案 2 :(得分:0)
有几点:
get_pointer_to_struct
只需返回malloc
的结果即可。并更改它的签名以避免额外的强制转换为my_struct*
。temp_array
是在堆栈上创建的,因此当init_pointers_array
退出时它不再存在。 malloc
它也是。这是你最大的问题。