从 2D 数组复制(行)到 1D 数组
Copy (row) from 2D array to 1D array
所以我有一个二维数组多数组[a][b]和另一个数组buf[b]。
我在分配"buf"等于多数组的一行时遇到问题。执行此操作的确切语法是什么?
// a 2-D array of char
char multiarray[2][5] = { 0 };
// a 1-D array of char, with matching dimension
char buf[5];
// set the contents of buf equal to the contents of the first row of multiarray.
memcpy(buf, multiarray[0], sizeof(buf));
数组不可分配。这没有核心语言语法。C++中的数组复制是在库级别或用户代码级别实现的。
如果这应该是C++的,并且如果您确实需要创建 2D 数组mutiarray
的某些行i
的单独副本buf
,那么您可以使用std::copy
#include <algorithm>
...
SomeType multiarray[a][b], buf[b];
...
std::copy(multiarray[i], multiarray[i] + b, buf);
或 C++11
std::copy_n(multiarray[i], b, buf);
我读到代码在snort(旧版本)中具有类似的功能,它是从tcpdump借来的,可能对您有所帮助。
/****************************************************************************
*
* Function: copy_argv(u_char **)
*
* Purpose: Copies a 2D array (like argv) into a flat string. Stolen from
* TCPDump.
*
* Arguments: argv => 2D array to flatten
*
* Returns: Pointer to the flat string
*
****************************************************************************/
char *copy_argv(char **argv)
{
char **p;
u_int len = 0;
char *buf;
char *src, *dst;
void ftlerr(char *, ...);
p = argv;
if (*p == 0) return 0;
while (*p)
len += strlen(*p++) + 1;
buf = (char *) malloc (len);
if(buf == NULL)
{
fprintf(stderr, "malloc() failed: %sn", strerror(errno));
exit(0);
}
p = argv;
dst = buf;
while ((src = *p++) != NULL)
{
while ((*dst++ = *src++) != ' ');
dst[-1] = ' ';
}
dst[-1] = ' ';
return buf;
}
如果您使用的是向量:
vector<vector<int> > int2D;
vector<int> int1D;
您可以简单地使用向量的内置赋值运算符:
int1D = int2D[A];//Will copy the array at index 'A'
如果您使用的是 c 样式数组,则原始方法是将所选行中的每个元素复制到一维数组:
例:
//Assuming int2D is a 2-Dimensional array of size greater than 2.
//Assuming int1D is a 1-Dimensional array of size equal to or greater than a row in int2D.
int a = 2;//Assuming row 2 was the selected row to be copied.
for(unsigned int b = 0; b < sizeof(int2D[a])/sizeof(int); ++b){
int1D[b] = int2D[a][b];//Will copy a single integer value.
}
语法是一条规则,算法是您可能的意思/期望的。
相关文章:
- C++使用数组作为多维数组,尽管将其初始化为带有指针的 1D
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- 如何使用指针C++将元素从2D数组复制到1D数组
- 借助功能将 2D 转换为 1D 数组
- 使用C++将1D数组转换为2D字符串数组
- C++ 矩阵乘法 2D 数组比 1D 更快
- 使用 std::transform 在 2d C 阵列上转换为 1d C 数组
- 在 C++ 中,用于将大型 2D 数组转换为 1D 数组的内存分配
- 将指向 1D Fortran 数组的指针传递给使用 C_LOC() 进行C++会导致垃圾值
- 表示为 1D 的多维数组(模板化为 n 维)
- 我的算法在 1D 数组中渲染矩形有什么问题
- 如何在C++中将 2d 矢量转换为 1d 数组?
- 在 C++ 中实现 1D 数组中的 2D 数组坐标
- 访问表示 2D 矩阵的 1D 存储数组
- C 将1D动态数组施放到2D数组以使用常规索引(例如ARR [i] [J])
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- C++ 3D 数组到 1D 会导致堆缓冲区溢出
- 我在将 cv::Mat 保存到 1D 数组时遇到问题
- C ,将1D数组转换为2D数组
- 数组 1D 我需要要求用户检查索引和打印值