重新分配指向结构的指针

时间:2016-09-10 21:03:38

标签: c pointers struct malloc realloc

我有一个问题理解这一点,我的代码如下:

#include <stdio.h>
#include <stdlib.h>
typedef struct mee test;
typedef struct aa fill;

struct aa {
    int c;
    fill *point;

};
struct mee {
    char name;
    fill **a;
    int b;
};
static fill **store;
static fill *talloc(int tsize);
static int mem;
static int ptr;
static fill *talloc(int tsize)
{   int temp;
    temp = ptr;
    ptr++;
    mem = mem + tsize;
    store = realloc(store, mem*sizeof(fill));
    store[temp] = malloc(sizeof(fill));
    return store[temp];
}

int main() {
    test *t;
        t = malloc(sizeof(test));
    t->a = malloc(sizeof(fill *)*10);
        printf("where\n");

    for(int i= 0; i < 10; i++) {        
        t->a[i] = talloc(1);
    }
    printf("%d\n", store[9]->c); //Problem here
    return 0;
}

原谅可怕的名字,只是一个更大项目的测试代码。此代码编译并运行正常。如果我设置代码:

printf("%d\n", store[9]->c);

存储[0-7]我得到0作为输出,虽然为什么8-9给我一些胡言乱语的负数?我假设它失去了它指针的某个地方。 我怎么能纠正这个?

对于某些背景知识,这是在数组中存储指向struct的指针,这样我以后就可以轻松地释放它们了。

0 个答案:

没有答案