如何插入,将新元素添加到char数组中

时间:2015-12-11 20:09:15

标签: arrays

我有把前面的新元素推送到char数组的问题。我在我的程序中有一个函数,它接受两个参数:一个指向char数组的指针,以及一个指向int的指针。此函数使用一些数据填充数组,并返回此数组中元素的数量。

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 之后,我只保存了两个大小的字节。为什么我看不到来自 buffer 的数据?

最后我想要在前面创建两个新字节的新表。这两个字节是大小旧表。假设收到的数据只有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'};

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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]中。

应该建议结构。