c - 当我更改参数时数组会更改

标签 c

所以我在c中有这段代码。一切正常,直到我再次读取单词。它获取新单词,但 (*A)[size-1] 也获取新单词的价格.我该如何防止这种情况发生?

void fuction(char ***A,char ***B,int size)
{
    char word[20],word2[20];
    printf("Type word .\n");
    gets(word);
    while(strcmp(word,"0")!=0)
    {
        printf("Type second word.\n");
        gets(word2);
        printf("%d",size);
        **A=realloc(**A,(size+1)*sizeof(char));
        **B=realloc(**B,(size+1)*sizeof(char));

        (*A)[size-1]=word;
        (*B)[size-1]=word2;

        size++;

        printf("Type another word to add or 0 to exit.\n");//**it all works fine** 
        gets(word);
    }
}

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void function(char ***A, char ***B, int *size){
    char word[32], word2[32];

    printf("Type first word.\n");
    scanf("%31s", word);
    while(strcmp(word,"0")!=0){
        printf("Type second word.\n");
        scanf("%31s", word2);
        *A =realloc(*A, (*size+1)*sizeof(char*));
        *B =realloc(*B, (*size+1)*sizeof(char*));
        (*A)[*size]=strdup(word);
        (*B)[*size]=strdup(word2);

        ++*size;

        printf("Type another word to add or 0 to exit.\n");
        scanf("%31s", word);
    }
}

int main(void){
    int i, size = 0;
    char **w1, **w2;
    w1 = w2 = NULL;
    function(&w1, &w2, &size);
    for(i = 0; i < size; ++i){
        printf("%s, %s\n", w1[i], w2[i]);
        free(w1[i]);free(w2[i]);
    }
    free(w1);free(w2);
    return 0;
}

关于c - 当我更改参数时数组会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27830908/

相关文章:

c++ - 在 C/C++ 中使用 itoa 将整数转换为二进制字符串

c - C 编程语言(第二版): Exercise 1-15 (Celsius to Fahrenheit conversion) - What is wrong with my solution?

c - 尝试使用整个 rand() 表是个好主意吗?

c - c 中的定义和逻辑,微处理器

c - 尝试将多个源文件与 C 中的一个 header 链接

c - 最重要的位在左边吗?

c - 关于使用函数、指针和动态分配的练习 (C)

c - get_nprocs() 和 get_nprocs_conf() -- 如何进行错误检查

Rust 中的 C 抽象数据类型

c - 2Darray 中的第二个标签 [1st][2nd] 含义是什么,例如 .char label[11][6]