I am trying to create an array of c string in C, which simulates a behavior similar to that of vector array in c++. The array doubles its capacity whenever the (currentSize + 1) is equal to (MAX_SIZE). This is how I am doing it:
我试图在C中创建一个c字符串数组,它模拟类似于c ++中向量数组的行为。只要(currentSize + 1)等于(MAX_SIZE),阵列就会使其容量加倍。这就是我这样做的方式:
void addLog(char ** dynamicArray, int* size, int *maxSize, int command){
if (*size < *maxSize){
dynamicArray[*size] = "User selects option 1 from main menu.";
(*size)++;
}
else{
//resizing the array here
int originalSize = *maxSize;
*maxSize = *maxSize * 2;
//copy elements of dynamic array in temporary array
char **tempArray = (char**)malloc(originalSize * sizeof(char*));
for (int i = 0; i < originalSize; ++i){
memcpy(&tempArray[i], &dynamicArray[i], sizeof(dynamicArray[i]));
}
//create new array of max * 2 size
dynamicArray = (char**)malloc(*maxSize * sizeof(char*));
//copy temp to dynamic
for (int i = 0; i < originalSize; ++i){
memcpy(&dynamicArray[i], &tempArray[i], strlen(tempArray[i]));
}
for (int i = 0; i < originalSize; i++) {
free(tempArray[i]); <---- this throws an exception on heap
}
free(tempArray);
//insert new element now
dynamicArray[*size] = "User selects option 1 from main menu.";
(*size)++;
}
}
I believe this is a trivial problem for a deep copy scenario. How to resize dynamic array to 2 * capacity and then free the temporary existing elements?
我相信这对于深拷贝场景来说是一个微不足道的问题。如何将动态数组的大小调整为2 *容量然后释放临时现有元素?
1 个解决方案
#1
3
You could create a reusable implementation yourself by extending a struct.
您可以通过扩展结构来自己创建可重用的实现。
This is a bit long, but it walks you through the entire process and should have everything you need to know:
这有点长,但它会引导您完成整个过程,并且应该包含您需要知道的所有内容:
http://eddmann.com/posts/implementing-a-dynamic-vector-array-in-c/
The structure will take advantage of a fixed-size array, with a counter invariant that keeps track of how many elements are currently present. If the underlying array becomes exhausted, the addition operation will re-allocate the contents to a larger size, by way of a copy."
该结构将利用固定大小的数组,具有计数器不变量,可跟踪当前存在的元素数量。如果基础数组耗尽,则添加操作将通过副本将内容重新分配给更大的大小。“
#1
3
You could create a reusable implementation yourself by extending a struct.
您可以通过扩展结构来自己创建可重用的实现。
This is a bit long, but it walks you through the entire process and should have everything you need to know:
这有点长,但它会引导您完成整个过程,并且应该包含您需要知道的所有内容:
http://eddmann.com/posts/implementing-a-dynamic-vector-array-in-c/
The structure will take advantage of a fixed-size array, with a counter invariant that keeps track of how many elements are currently present. If the underlying array becomes exhausted, the addition operation will re-allocate the contents to a larger size, by way of a copy."
该结构将利用固定大小的数组,具有计数器不变量,可跟踪当前存在的元素数量。如果基础数组耗尽,则添加操作将通过副本将内容重新分配给更大的大小。“