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

标签 c arrays string malloc dynamic-arrays

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

#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 返回一个指向重新分配的内存块的指针,您需要一个三重指针来传递(并使用解引用运算符操作它的值)一个指向字符串的指针:

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);

关于c - 将字符串添加到字符串数组会以某种方式更改数组中的先前字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943052/

相关文章:

java - 如何从文本区域中删除输入的数字?

php - 将文本框值存储在数组中

java - 空字符串对象和字符串文字的串联

c - 具有逻辑运算符的混合增量运算符

C 中的组合信号量和自旋锁?

c - 具有随机字符的随机长度字符串

arrays - C 字符串被替换与通过编辑 char 数组进行更改

java - 如何区分能被 2 整除和能被 4 整除?

java - 如何在字符串数组中搜索特定字符串

java - 是否可以使用字符串格式化程序自动换行?