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

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

问题描述

我正在寻找一种将多维字符数组复制到新目的地的智能方法.我想复制 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() credis.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 查找字符串的长度(必须以 null 结尾).

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 ++如何复制没有嵌套循环的多维char数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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