2015-12-11 233 views
-1

我推送新元素到char數組前面有問題。我在我的程序中有一個函數,它有兩個參數:一個指向char數組的指針和一個指向int的指針。該函數用一些數據填充數組,並返回此數組中元素的數量。如何插入,將新元素添加到char數組中

int function1(char* buffer , int* outSize); 

buffer[1000] 
int size; 
result = function1(buffer , &size); 

// after this a get some data in buffer and count how many data is in buffer. let's say 456 elements 
// now a try push to front two new bytes as size this array 

finallBuffer *char = new char[size+2]; 
memcpy(finallyBuffer, (char*)&size, 2); // here a get size in two bytes and put to finnalBuffer 

// next I try just copy to finnalyBuffer received data from Buffer 
strcat(finallyBuffer , buffer); 
doSomething(finallyBuffer); 
delete []finallyBuffer; 

在此之後在finnalyBuffer我只保存大小兩個字節。爲什麼我看不到來自緩衝區的數據

在最後我要實現新表在前面的兩個新的字節。這兩個字節是大小舊的表。比方說,接收到的數據HEVE只有5個字符

char table[5] = {'a','b','b','c','t'};

所以尺寸爲5.5兩個字節是char size = {'5','0'};

結果應該是的樣子。

char table[5] = {'5','0','a','b','b','c','t'};

+0

你是什麼意思「推到前面」? – Olaf

+0

這不是C.不要添加不相關的標籤。 – Olaf

+0

你有沒有考慮過使用'struct'?它將有2個成員:'int numBytesRead;字符緩衝區[1000]'。 –

回答

1

我不知道確切地知道你想要做什麼,但我試圖理解它。在代碼見下面的意見,我希望它會幫助你。

int function1(char* buffer , int* outSize); 

buffer[1000] 
int size; 
result = function1(buffer , &size); 

// after this a get some data in buffer and count how many data is in buffer. let's say 456 elements 
// now a try push to front two new bytes as size this array 

char *finallBuffer = new char[size*sizeof(char)+2]; 
short ssize = (short)size; 
memcpy(finallyBuffer, &ssize, 2); // here a get size in two bytes and put to finnalBuffer 

// next I try just copy to finnalyBuffer received data from Buffer 

/* NOTE: strcat is for null terminated string. If i understand what you want 
    to do you want store int in 4 bytes ? 
    I assume size is the actual size of the buffer 
*/ 
//strcat(finallyBuffer , buffer); 
memcpy(&finallyBuffer[2], buffer, sizeof(char)*size); 
doSomething(finallyBuffer); 
delete []finallyBuffer; 
+0

我的目的很簡單。假設我收到的數據看起來像'char table [5] = {'s','b','v','h','j'}'現在我想**推入,插入前面**兩個字節,所以現在新的table1應該看起來像'char table1 [7] = {'x','x','s','b','v','h','j'}'。 Thx提前。 – Mbded

+1

所以你想將大小轉換爲16位(總是<65536)? –

+0

是的,我想將大小轉換爲2個字節,並且在插入之後,將這兩個字節推到前面,作爲[0],[1]元素到新表char。例如在Qt庫中,我可以用這種方式http://doc.qt.io/qt-5/qstring.html#prepend – Mbded

0

那些線接錯:

finallBuffer *char = new char[size+2]; 
memcpy(finallyBuffer, (char*)&size, 2); 

他們應該是:

char * finalBuffer = new char[size+2]; 
memcopy(finallyBuffer, buffer, size); 

但我真的理解你正在嘗試做一些事情。

編輯:

現在我看到你在做什麼,奧利弗給了你答案。如果你不想(或不能)爲你的緩衝區使用std :: vector,那麼無論如何你都可以節省重新分配數組的代價。

  • 剛開始爲緩衝區2分配更多字節:char buffer[1002];
  • 然後要存儲值,您可以將指針傳遞給第三個元素:char* ptr = buffer + 2;
  • 當你知道這些數據的實際尺寸,只是把字節buffer[0]buffer[1]

一個結構應建議。

+0

我想複製到[0]和[1]只有2個大小爲兩個字節.Thx爲答案 – Mbded