#include<stdlib.h>
typedef struct HEAP_
{
int size;
void **tree;
int (*compare)( const void *key1,const void *key2);
void (*destroy) (void *data);
}Heap;
int main()
{
Heap *H;
void *temp;
H=(Heap*)malloc(sizeof(Heap));
if ((temp = (void **)realloc(H->tree, (5) * sizeof (void *))) == NULL) return -1;
H->tree=temp;
int a=0001;
int b=0002;
H->tree[0]=&a;
H->tree[1]=&b;
//*(int*)H->tree[0]=0001;
//*(int*)H->tree[1]=0002;
//printf("%d %d %d %d %d",H->tree[0],H->tree[1],H->tree,*(int*)H->tree[0],*(int*)H->tree[1],*(int*)*H->tree);
//printf("%d %d %d ",*(int*)H->tree[0],*(int*)H->tree[1],*(int*)*H->tree);
我想弄清楚这些结果的种类,例如地址用完了,数字用完了 // printf(“%d%d”,(int )H-> tree [0],(int )H-> tree [1]); >
printf("%d %d ", *(int*)H->tree[0] , *(int*)H->tree[1]);
return 0;
}
当我构建并运行它时,编译器告诉我,最后一个无法打印,我该如何解决?似乎我误解了指针。
答案 0 :(得分:0)
您已为该结构分配了内存:
H=(Heap*)malloc(sizeof(Heap));
,但是您没有为其成员树分配内存。您还需要这样做:
H->tree = malloc(required_size);
所以您的工作代码如下:
#include<stdlib.h>
#include<stdio.h>
typedef struct HEAP_
{
int size;
void **tree;
int (*compare)( const void *key1,const void *key2);
void (*destroy) (void *data);
}Heap;
int main() {
Heap *H;
void *temp;
H=malloc(sizeof(Heap));
H->tree=NULL;
if((temp = malloc(5*sizeof(void *))) == NULL)
return -1;
H->tree=temp;
int a;
a=1;
int b;
b=4;
H->tree[0]=&a;
H->tree[1]=&b;
printf(" %d\n ", *(int *)H->tree[0]);
printf(" %d\n ", *(int *)H->tree[1]);
return 0;
}
答案 1 :(得分:0)
Here the answer :
您需要为堆分配内存,如下所示,
H=(Heap*)malloc(sizeof(Heap));
您也为双指针分配了内存。
H-> tree = malloc(sizeof(int **) 2 / 指针数量* /);
H-> tree [0] =(int *)malloc(sizeof(int));
H-> tree [1] =(int *)malloc(sizeof(int));
将值分配给tree [0],如下所示,
*((int*)H->tree[0]) = 25;
工作代码如下:
typedef struct HEAP_
{
int size;
void **tree;
int (*compare)( const void *key1,const void *key2);
void (*destroy) (void *data);
}Heap;
int main()
{
Heap *H;
H=(Heap*)malloc(sizeof(Heap));
H->tree = malloc(sizeof(int**)*2);
H->tree[0]=(int*)malloc(sizeof(int));
H->tree[1]=(int*)malloc(sizeof(int));
*((int*)H->tree[0]) = 25;
printf("%d",*((int*)H->tree[0]));
return 0;
}