且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C/C++ 如何在没有嵌套循环的情况下复制多维字符数组?

更新时间:2022-11-03 19:19:48

你可以使用 memcpy.

You could use memcpy.

如果多维数组大小在编译时给出,即mytype myarray[1][2],那么只需要一个memcpy调用

If the multidimensional array size is given at compile time, i.e mytype myarray[1][2], then only a single memcpy call is needed

memcpy(dest, src, sizeof (mytype) * rows * columns);

如果,就像你指出的数组是动态分配的,你需要知道两个维度的大小,因为动态分配时,数组中使用的内存不会在一个连续的位置,这意味着 memcpy将不得不多次使用.

If, like you indicated the array is dynamically allocated, you will need to know the size of both of the dimensions as when dynamically allocated, the memory used in the array won't be in a contiguous location, which means that memcpy will have to be used multiple times.

给定一个二维数组,复制它的方法如下:

Given a 2d array, the method to copy it would be as follows:

char** src;
char** dest;

int length = someFunctionThatFillsTmp(src);
dest = malloc(length*sizeof(char*));

for ( int i = 0; i < length; ++i ){
    //width must be known (see below)
    dest[i] = malloc(width);

    memcpy(dest[i], src[i], width);
}

鉴于您的问题看起来您正在处理一个字符串数组,您可以使用 strlen 查找字符串的长度(必须以空字符结尾).

Given that from your question it looks like you are dealing with an array of strings, you could use strlen to find the length of the string (It must be null terminated).

在这种情况下,循环会变成

In which case the loop would become

for ( int i = 0; i < length; ++i ){
    int width = strlen(src[i]) + 1;
    dest[i] = malloc(width);    
    memcpy(dest[i], src[i], width);
}