2017-06-13 68 views
0

早上好! 我必须处理一个模拟列表的结构数组(全局变量)。实际上,每次我调用方法时,我都必须增加数组1的大小并将其插入到新结构中。模拟数组列表

由于数组的大小是静态的,我的想法是使用指针这样的:

  1. 的结构数组被声明为指针的第二结构阵列。
  2. 每次我调用increaseSize()方法时,旧数组的内容都被复制到一个新的n + 1数组中。
  3. 全局数组指针被更新为指向一个新的数组

从理论上讲,该解决方案似乎很容易......但我℃的小白。哪里错了?

struct task { 
    char title[50]; 
    int execution; 
    int priority; 
    }; 

    struct task tasks = *p; 


int main() { 
    //he will call the increaseSize() somewhere... 
} 

void increaseSize(){ 

    int dimension = (sizeof(*p)/sizeof(struct task)); 

    struct task newTasks[dimension+1]; 

    for(int i=0; i<dimension; i++){ 

     newTasks[i] = *(p+i); 

    } 

    free(&p); 

    p = newTasks; 
} 
+2

'sizeof(* p)/ sizeof(struct task)'看起来很可疑 – harold

+0

'struct task tasks = * p;''p是什么? – joop

+0

p应当是当前任务链接到 –

回答

1

在这里混淆了很多!

int dimension = (sizeof(*p)/sizeof(struct task)); 

p是一个指针,*p指向struct task,所以sizeof(*p)将等于sizeof(struct task),和尺寸始终将1 ...

在这种情况下,你不能使用sizeof。您将不得不将尺寸(元素数量)存储在单独的变量中。

struct task newTasks[dimension+1]; 

这将创建一个新的数组,是–但范围只在当前函数(所以通常情况下,它是在栈上分配)。这意味着一旦离开功能,阵列将被重新清理。

你需要的是在堆上创建数组。您需要为(或calloc或realloc)使用malloc函数。

此外,我建议不增加数组1,而是重复其大小。不过,您还需要存储包含在其中的元素数量。

把所有在一起:

struct task* p; 
size_t count; 
size_t capacity; 

void initialize() 
{ 
    count = 0; 
    capacity = 16; 
    p = (struct task*) malloc(capacity * sizeof(struct task)); 
    if(!p) 
     // malloc failed, appropriate error handling! 
} 

void increase() 
{ 
    size_t c = capacity * 2; 
    // realloc is very convenient here: 
    // if allocation is successful, it copies the old values 
    // to the new location and frees the old memory, so nothing 
    // so nothing to worry about except for allocation failure 
    struct task* pp = realloc(p, c * sizeof(struct task)); 
    if(pp) 
    { 
     p = pp; 
     capacity = c; 
    } 
    // else: apprpriate error handling 
} 

最后,为完成:

void push_back(struct task t) 
{ 
    if(count == capacity) 
     increase(); 
    p[count++] = t; 
} 

删除元素留给你–你不得不全部复制后续元素一个位置再少减少计数。

+1

*这将创建一个新的数组,是的 - 但在堆栈上*我认为更好的措辞是它将创建一个函数局部范围的数组。 C标准没有堆栈。 –

+0

@AjayBrahmakshatriya我认为这是一个更糟的措辞。使用这种纯粹的标准术语会让人难以理解(特别是对于那些显然是像OP这样的初学者的人),并且这种细微差别在这里是无关紧要的。即使不可能将其分配到堆栈上,将其解释为好像不是有害的。 – harold