复制多维数组(指针) [英] copying multidimensional array (pointers)
问题描述
我有两个指向指针的结构指针
I have two structs pointers to pointers
typedef struct Square {
...
...
}Square;
Square **s1; //Representing 2D array of say, 100*100
Square **s2; //Representing 2D array of say, 200*200
两者都使用malloc()
在堆上分配.
我已经将s1
初始化为某些值,并且将s2
完全初始化为默认值.
基本上,我需要将s1
的大小调整为<c2>的大小,同时保持其(s1
)值,并且添加的"值将与它们在s2
中的默认值一样.
Both are allocated on the heap using malloc()
.
I have s1
initialized with certain values and s2
initialized completely with the default values.
Basically I need to resize s1
to the size of s2
while maintaining its (s1
) values, and the 'added' values would be just as they were in s2
- the default value.
我写了这个问题 memcpy()从较小的数组到较大的数组但显然我在数组和指针之间感到困惑/
I wrote this question memcpy() from smaller array to larger one but apparently I'm confusing between arrays and pointers/
我的问题是,如何实现将s1
的大小调整为<c2>的大小.我不必保留原始指针.我可以将s1
复制到s2
并返回s2
(如果这样更好)
我希望我能正确解释我的要求.
谢谢!
My question is, how to implement this resizing of s1
to the size of s2
. I don't have to keep the original pointer. I can copy s1
to s2
and return s2
if that's a better way
I hope I explained what I'm after properly.
Thanks!
推荐答案
二维数组按顺序排列在内存中:row1 row2 row3等.
Two dimensional arrays are laid out in memory sequentially: row1 row2 row3 etc.
memcpy从一个内存位置到另一个内存位置进行线性复制.
memcpy does a linear copy from one memory location to another.
因此,实现您所需要的:
So to achieve what you need:
a)创建一个新数组
Square **s3 = malloc(sizeof(s2));
b)将s2复制到其中
b) Copy s2 into it
c)将s1中的内容逐行复制到新内容中
c) Copy stuff from s1, row by row into new
for(r = 0; r < NROWS_S1; r++)
memcpy(s3[r], s1[r], sizeof(Square) * NCOLS_S1);
http://www.fredosaurus. com/notes-cpp/arrayptr/23two-dim-array-memory-layout.html
这篇关于复制多维数组(指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!