如何在c中的字符串数组中添加字符串?

时间:2016-12-20 22:27:05

标签: c string

我正在尝试将字符串添加到数组中,但我不确定这段代码是如何工作的。有人可以给我一些反馈意见吗?

this.Before(()=> {
  this.browser.restart();
})

当我运行代码时,核心转储,但我不明白为什么

我问的原因是因为我知道传递数组的大小很容易。但对于这种方法,我不被允许。 Unfortunatley,我的教授确实说功能参数必须保持不变

1 个答案:

答案 0 :(得分:1)

有几个问题,例如sizeof (array) + sizeof (char*)sizeof(array)错误,+也是*;以上所有其他评论也适用。

写了一个解决方案并将你的代码留作评论;看到差异。

/* Exercise b: Add <string> to the end of array <array>.
 * Returns: pointer to the array after the string has been added.
 */
char **add_string(char **array, const char *string) {

    int lastIndex = 0;
    while (array[lastIndex] != nullptr)
        lastIndex++;

    /*reallocate so the array of strings can hold one more string; note that lastIndex is zero-based; hence, the size of the current array is lastIndex+1, and consequently the size of the new array needs to be lastIndex+2 */
    // char** newArray = (char**)realloc(array, sizeof (array) + sizeof (char*));
    char** newArray = (char**)realloc(array, (lastIndex+2) * sizeof (char*));
    if (!newArray) return array;

    /*allocate memory for new string*/
    char* newString = strdup(string);
    //char* newString = malloc(strlen(string) * sizeof (char));
    if (!newString) return newArray;

    /*copy old string to new string*/
    //int lastIndex = sizeof (newArray) / sizeof (char*);
    //strncpy(newString,string,strlen(string));


    /*null terminate array and set old end of array to new string*/
    //newArray[lastIndex] = NULL;
    //newArray[lastIndex-1] = newString;

    newArray[lastIndex++] = newString;
    newArray[lastIndex] = nullptr;

    return newArray;
}

void printArray (char** array) {
    char* str; int i=0;
    while ((str = array[i]) != nullptr) {
        std::cout << i << ":" << str << std::endl;
        i++;
    }
}

int main() {

    char** myArray = (char**) malloc(1 * sizeof(char*));
    myArray[0] = nullptr;

    std::cout << "empty:" << std::endl;
    printArray (myArray);

    myArray = add_string(myArray, "Tom");
    std::cout << "one element:" << std::endl;
    printArray (myArray);

    myArray = add_string(myArray, "Jerry");
    myArray = add_string(myArray, "Fin");
    std::cout << "three elements:" << std::endl;
    printArray (myArray);

    return 0;
}