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

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

问题描述

我在找一个聪明的办法,以多维字符数组复制到一个新的目的地。我要复制的字符数组,因为我想在不改变源阵列编辑内容。

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).

在code是这样的:

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的Ç的lib 函数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 *

But I'm getting a: *Program received signal: 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 * coloumns);

如果,像您所指示的阵列是动态分配的,则需要知道两个维度的大小时动态分配为,在阵列中使用的存储器将不会在一个连续的位置,这意味着的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.

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

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