将字符串添加到字符串数组会以某种方式更改数组中的先前字符串

Adding strings to an array of strings is somehow changing the previous strings in the array

我编写这个函数的目的是将字符串添加到字符串数组中,每次在放入新字符串之前为新字符串创建足够的内存,并realloc获取数组的大小满的。这是我的代码示例:

#define INITIAL 10

int addtoarray(char **A, int *size, int n, char *b);

int
main(int argc, char **argv) {
    char **D, a[3]="ab"; /*'a' is arbitrary for this example */
    int n=0, size=INITIAL, i, j;

    D = (char**)malloc(INITIAL*sizeof(char));

    for (i=0; i<3; i++) {
        n = addtoarray(D, &size, n, a);

        /* print the contents of D */
        printf("Dict: ");
        for (j=0; j<n; j++) {
            printf("D[%d]='%s' ", j, D[j]);    
        } printf("\n");
    }

    return 0;
}

int
addtoarray(char **A, int *size, int n, char *b) {

    if (*size == n) {
        /* Array is full, give more space */ 
        realloc(A, *size = 2*(*size));
        assert(A);
    }

    printf("Adding '%s' to D[%d], size of D = %d\n", b, n, *size);

    /* Create space in array for new string */
    A[n] = (char*)malloc(strlen(b)+1);
    assert(A[n]);

    /* Put the new string in array! */
    strcpy(A[n], b);
    n++;

    return n;
}

在此示例中,'n' 是数组中的字符串数。这段代码的输出是:

Adding 'ab' to D[0], size of D = 10
D: D[0]='ab' 
Adding 'ab' to D[1], size of D = 10
D: D[0]='ab' D[1]='ab' 
Adding 'ab' to D[2], size of D = 10
D: D[0]='?K@S?' D[1]='ab' D[2]='ab'

如您所见,第三次调用该函数时,字符串很好地进入了数组。但是数组中的第一个字符串以某种方式改变了。我不知道为什么会发生这种情况,但我很确定它发生在函数的 A[n] = (char*)malloc(strlen(b)+1); 行上。

有谁知道我做错了什么? (此外,如果您对我的代码的其他部分有任何提示)

如果你想要一个字符串数组,你需要 char *:

大小的空间
malloc(INITIAL*sizeof(char));

应该是

malloc(INITIAL*sizeof(char *));

并且在 realloc 部分:

realloc(A, *size = 2*(*size));

正如 Jonathan Leffler 所指出的,realloc returns 指向重新分配的内存块的指针,您需要一个三重指针来传递(并使用取消引用运算符操作其值)指向字符串:

int addtoarray(char ***A, int *size, int n, char *b) {
   ...
   *A = realloc(*A, (*size = 2*(*size)) * sizeof(char *));
   assert(*A);
   ...

并在您的 main 函数中:

n = addtoarray(&D, &size, n, a);

发生这种情况是因为您没有分配从 realloc 返回的指针。

realloc(A, *size = 2*(*size));

应该是:

A = realloc(A, *size = 2*(*size));

没有这个,A 仍然指向旧内存 space。