gpt4 book ai didi

在C程序中将2个数组复制到1个数组

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

如何将 2 个独立的 2D 数组复制到 1 个数组中,我在下面描述了我的意思:

我有 1 个数组:a、b、c我有第二个数组:d、e、f

我希望第三个数组具有上述两个数组:第三个数组:a、b、c、d、e、f

到目前为止,我的代码只是获取两个数组的值,并且在打印第三个数组时我注释掉了:

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

int main(){
int i,j,count;

char ar1[3][10]={"a","b","c"};
char ar2[3][10]={"d","e","f"};
char ar3[6][10];

for (i=0;i<3;i++){
printf("%s\n",ar1[i]);
}
for (i=0;i<3;i++){
printf("%s\n",ar2[i]);
}
printf('new array:\n');
// for (i=0;i<6;i++)
// printf("%s\t\n",ar3[i]);
}

最佳答案

由于数组最右边的维度相等,因此将两个数组复制到一个数组中的最简单方法如下

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

int main(void)
{
char ar1[3][10] = { "a", "b", "c" };
char ar2[3][10] = { "d", "e", "f" };
char ar3[6][10];

memcpy( ar3, ar1, sizeof( ar1 ) );
memcpy( ar3 + 3, ar2, sizeof( ar2 ) );

for ( size_t i = 0; i < 6; i++ )
{
puts( ar3[i] );
}

return 0;
}

输出为

a
b
c
d
e
f

另一种方法是使用函数 strcpy 单独复制每个字符串

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

int main(void)
{
char ar1[3][10] = { "a", "b", "c" };
char ar2[3][10] = { "d", "e", "f" };
char ar3[6][10];

size_t j = 0;
for ( size_t i = 0; i < 3; i++, j++ )
{
strcpy( ar3[j], ar1[i] );
}

for ( size_t i = 0; i < 3; i++, j++ )
{
strcpy( ar3[j], ar2[i] );
}

for ( size_t i = 0; i < 6; i++ )
{
puts( ar3[i] );
}

return 0;
}

输出将与上面相同

a
b
c
d
e
f

关于在C程序中将2个数组复制到1个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26714225/

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