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

时间:2012-11-17 02:09:29

标签: c++ multidimensional-array

所以我有一个2d阵列多阵列[a] [b]和另一个阵列buf [b]。

我无法将'buf'指定为等于多阵列的其中一行。这样做的确切语法是什么?

4 个答案:

答案 0 :(得分:3)

// 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)); 

答案 1 :(得分:1)

数组不可分配。这没有核心语言语法。 C ++中的数组复制是在库级或用户代码级实现的。

如果这应该是C ++,并且您确实需要为2D数组buf的某些行i创建单独的副本 mutiarray,然后你可以使用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);

答案 2 :(得分:0)

我在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: %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;

}

答案 3 :(得分: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.
}

语法是一个规则,算法就是你可能想要/想要的。

相关问题