2011-05-05 108 views
2

我是新来的c。我想创建数组,然后将其删除,然后将另一个数组放入其中。我该怎么做?C:删除阵列

+1

你能告诉我们你是如何分配数组的吗?如果你使用malloc,你可以使用free来释放它,然后分配一个新的。 – 2011-05-05 14:52:53

+0

是的,我用malloc – Tom 2011-05-05 14:55:18

+0

如果你使用malloc,你有代码。如果你有代码,你应该发布它。 – abelenky 2011-05-05 15:17:55

回答

5

如果您在C中寻找动态数组,它们相当简单。

1)声明一个指针来跟踪存储器,
2)分配内存,
3)使用存储器,
4)释放内存。

int *ary; //declare the array pointer 
int size = 20; //lets make it a size of 20 (20 slots) 

//allocate the memory for the array 
ary = (int*)calloc(size, sizeof(int)); 

//use the array 
ary[0] = 5; 
ary[1] = 10; 
//...etc.. 
ary[19] = 500; 

//free the memory associated with the dynamic array 
free(ary); 

//and you can re allocate some more memory and do it again 
//maybe this time double the size? 
ary = (int*)calloc(size * 2, sizeof(int)); 

calloc()信息可以发现here,同样的事情可以用malloc()通过,而不是使用malloc(size * sizeof(int));

2

这听起来像你问是否可以重新使用指针变量指向完成分配给不同时间的堆分配区域。是你可以:

void *p;   /* only using void* for illustration */ 

p = malloc(...); /* allocate first array */ 
...    /* use the array here */ 
free(p);   /* free the first array */ 

p = malloc(...); /* allocate the second array */ 
...    /* use the second array here */ 
free(p);   /* free the second array */