gpt4 book ai didi

连接两个二维字符数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:35 27 4
gpt4 key购买 nike

我写了一个小程序来组合两个二维数组。这是代码:

#define MAX 7

int main(void) {
int i, j;
char *array1[] = {"Welt,", "bist", "du"};
char *array2[] = {"noch", "zu", "retten?"};

char final[MAX][MAX];
for(i = 0; i < 3; i++) {
// initialize ith names element with first name
strcpy(final[i], array1[i]);
}

for(j = 0; j < 3; j++) {
// concatenate the last name to the firstname+space string
strcat(final[i], array2[j]);
}

for (i = 0; i != 6; i++) {
printf("%s", final[i]);
}
return EXIT_SUCCESS;
}

我得到非常奇怪的输出,如:

Welt,bistbistdunochzuretten?uretten?en?

而我想要的是:

Welt,bistdunochzuretten

如您所见,这并非完全错误。单词之间不应有空格。

如何修复我的代码?

最佳答案

问题在于,在第二个 for 中,您正在执行 strcat(final[3], array2[j]);,因为 i 那时是 3,在最后的 for 中,你试图从 final[0] 打印到 final[5],当你只定义了 final[0]final[3] (在 final[0] 到 final[2] 你有名字,在 final[3] 你将所有姓氏连接在一起,这也超过了字符数限制),并且如果不在新行中打印它们,则很难分辨哪个字符串是什么。

试试这个。

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

#define MAX 7

int main(void) {
int i,j;
char *array1[] = {"Welt","bist","du"};
char *array2[] = {"noch","zu","retten?"};

char final[MAX][MAX];

for(i=0;i<3;i++)
strcpy(final[i], array1[i]); //To initialize ith names element with first name

for(j=0;j<3;j++)
strcat(final[j],array2[j]); //Concatanate the last name to the firstname+ space string

for (i = 0; i < 3; i++)
printf("%s\n", final[i]);

return EXIT_SUCCESS;
}

关于连接两个二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27345922/

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