【发布时间】:2017-06-13 10:16:37
【问题描述】:
早上好! 我必须处理一个模拟列表的结构数组(全局变量)。实际中,每次调用方法,都要增加数组1的大小,插入到新的struct中。
由于数组大小是静态的,我的想法是使用这样的指针:
- 结构数组被声明为指向第二个结构数组的指针。
- 每次调用increaseSize()方法时,都会将旧数组的内容复制到一个新的n+1数组中。
- 全局数组指针更新为指向新数组
理论上,解决方案似乎很简单……但我是 c 的菜鸟。哪里错了?
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;
}
【问题讨论】:
-
sizeof(*p) / sizeof(struct task)看起来很可疑 -
struct task tasks = *p;p是什么? -
顺便说一句,链表是你想要的实现细节——你想做的只是一个list。使用数组执行此操作实际上意味着
malloc()这个数组和realloc()它在增长时是必要的。 -
披露
bla bla bla。linked list和array这两个词是矛盾的。 -
p在哪里声明?但无论如何,p = newTasks;将不工作。