gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:30:57 25 4
gpt4 key购买 nike

所以我在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com