简体   繁体   English

如何将数组值复制到另一个数组

[英]How to copy array value to another array

I have two arrays:我有两个数组:

char roundNames1[16][25], roundNames2[16 / 2][25];

I then want to copy a result from the first array to the second.然后我想将结果从第一个数组复制到第二个数组。 I have tried this:我试过这个:

where roundNames1[5] = "hello"其中roundNames1[5] = "hello"

#include <string.h>

printf("First array: %s", roundNames1[5]);
strcpy(roundNames1[5], roundNames2[6]);
printf("Second array: %s", roundNames2[6]);

But this just returns但这只是返回

First array: hello
Second array:

Why is it not working?为什么它不起作用?

You need to exchange arguments of function strcpy您需要交换函数 strcpy 的参数

strcpy( roundNames2[8], roundNames1[5] );

Here is a part pf the function description from the C Standard这是 C 标准中函数描述的一部分

7.23.2.3 The strcpy function 7.23.2.3 strcpy 函数

Synopsis概要

1 1

#include <string.h>
char *strcpy(char * restrict s1, const char * restrict s2);

Description描述

2 The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. 2 strcpy 函数将s2 指向的字符串(包括终止空字符)复制到s1 指向的数组中。 If copying takes place between objects that overlap, the behavior is undefined.如果复制发生在重叠的对象之间,则行为未定义。

strcpy - arguments other way around. strcpy - 其他方式的争论。

http://www.cplusplus.com/reference/cstring/strcpy/ http://www.cplusplus.com/reference/cstring/strcpy/

Copy arrays/strings with memcpy使用memcpy复制数组/字符串

void * memcpy (void * destination, void * source, size_t size)

The memcpy function copies an certain amount of bytes from a source memory location and writes them to a destinaction location. memcpy函数从源内存位置复制一定数量的字节并将它们写入目标位置。

Example:例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
    char a[] = "stackoverflow";
    int s = sizeof(a);
    int c = s / sizeof(a[0]);
    char *p = malloc(s);
    memcpy(p, &a, s);
    printf("%s\n", p);
    free(p);
}

Output输出

$ ./a.out 
stackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM