C/C++ 如何在没有嵌套循环的情况下复制多维字符数组? [英] C / C++ How to copy a multidimensional char array without nested loops?

查看:27
本文介绍了C/C++ 如何在没有嵌套循环的情况下复制多维字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将多维字符数组复制到新目的地的智能方法.我想复制char数组,因为我想在不改变源数组的情况下编辑内容.

I'm looking for a smart way to copy a multidimensional char array to a new destination. I want to duplicate the char array because I want to edit the content without changing the source array.

我可以构建嵌套循环来手动复制每个字符,但我希望有更好的方法.

I could build nested loops to copy every char by hand but I hope there is a better way.

更新:

我没有2.级别维度的大小.给定的只是长度(行).

I don't have the size of the 2. level dimension. Given is only the length (rows).

代码如下:

char **tmp;
char **realDest;

int length = someFunctionThatFillsTmp(&tmp);

//now I want to copy tmp to realDest

我正在寻找一种将 tmp 的所有内存复制到空闲内存并将 realDest 指向它的方法.

I'm looking for a method that copies all the memory of tmp into free memory and point realDest to it.

更新 2:

someFunctionThatFillsTmp() 是 Redis C 库中的 credis_lrange() 函数 信用证.c.

someFunctionThatFillsTmp() is the function credis_lrange() from the Redis C lib credis.c.

在 lib tmp 里面创建:

Inside the lib tmp is created with:

rhnd->reply.multibulk.bulks = malloc(sizeof(char *)*CR_MULTIBULK_SIZE)

更新 3:

我已经尝试在这行中使用 memcpy:

I've tried to use memcpy with this lines:

int cb = sizeof(char) * size * 8; //string inside 2. level has 8 chars
memcpy(realDest,tmp,cb);
cout << realDest[0] << endl;

prints: mystring

但我得到一个:程序收到信号:EXC_BAD_ACCESS

推荐答案

你可以使用 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);
}

这篇关于C/C++ 如何在没有嵌套循环的情况下复制多维字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆