创建字符串的向量字符数组

Create vector char array of strings

我正在尝试在 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)++;
    }
}

我认为这对于深层复制场景来说是一个微不足道的问题。如何将动态数组的大小调整为 2 * 容量,然后释放临时存在的元素?

您可以通过扩展结构自己创建可重用的实现。

这有点长,但它会引导您完成整个过程,并且应该包含您需要知道的一切:

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."