从 2D 数组复制(行)到 1D 数组

Copy (row) from 2D array to 1D array

本文关键字:数组 1D 2D 复制      更新时间:2023-10-16

所以我有一个二维数组多数组[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.
}

语法是一条规则,算法是您可能的意思/期望的。