2

所以我有一个二维数组 multiarray[a][b] 和另一个数组 buf[b]。

我无法将“buf”指定为等于多数组的行之一。执行此操作的确切语法是什么?

4

4 回答 4

4
// 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)); 
于 2012-11-17T02:13:50.237 回答
2

数组不可赋值。对此没有核心语言语法。C++ 中的数组复制是在库级别或用户代码级别实现的。

如果这应该是 C++ 并且您确实需要创建2D 数组某行的单独副本 ,那么您可以使用bufimutiarraystd::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);
于 2012-11-17T02:14:43.420 回答
0

I read the code has similar function in snort (old version), it is borrowed from tcpdump, maybe helpful to you.

/****************************************************************************
 *
 * 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: %s\n", strerror(errno));
     exit(0);
  }
  p = argv;
  dst = buf;
  while ((src = *p++) != NULL)
  {
      while ((*dst++ = *src++) != '\0');
      dst[-1] = ' ';
  }
  dst[-1] = '\0';

  return buf;

}

于 2012-11-17T03:04:42.957 回答
0

如果您使用向量:

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

语法是规则,算法是您可能的意思/想要的。

于 2015-08-29T13:05:44.740 回答