2012-11-17 66 views
2

所以我有一個2d數組multifray [a] [b]和另一個數組buf [b]。從二維數組複製(行)到一維數組

我在分配'buf'等於多列陣的某一行時遇到了問題。什麼是確切的語法來做到這一點?

+0

你現在有哪些代碼? – Dai

+0

您不能分配數組。數組名稱不是左值。 – chris

+0

buf [0] =&multiarray [index];是我的。 @Chris,但數組被視爲像C中的指針,是嗎? – user1782677

回答

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

數組不可分配。這沒有核心語言的語法。 C++中的數組複製是在庫級別或用戶代碼級別實現的。

如果這應該是C++,如果你真的需要創建一個單獨的副本二維數組mutiarray的一些列ibuf,那麼你可以使用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); 
0

我讀的代碼中有打鼾(老版)類似的功能,它是從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; 

}

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

語法是一個規則,算法是什麼,你可能是指/所需。