C++ 向无符号字符指针添加短int

C++ 向无符号字符指针添加短int,c++,pointers,C++,Pointers,我正在寻找一种方法,将short int的字符串表示形式附加到现有字符串(存储在无符号字符*中) 我认为唯一可以做到这一点的方法是使用memcpy(),但如果这是我需要使用的东西,我想举个例子。这就是你想要的吗?这会将无符号字符*视为字符串,并向其“附加”短int的字符串表示形式 除了 1) 使用无符号字符表示字符串是非常不寻常的。我想说你的第一步是把它转换成一个普通的字符指针 2) 使用C风格字符串时,Printf是您最好的朋友 #include <stdio.h> #includ

我正在寻找一种方法,将
short int
的字符串表示形式附加到现有字符串(存储在
无符号字符*
中)


我认为唯一可以做到这一点的方法是使用
memcpy()
,但如果这是我需要使用的东西,我想举个例子。

这就是你想要的吗?这会将无符号字符*视为字符串,并向其“附加”短int的字符串表示形式

除了

1) 使用无符号字符表示字符串是非常不寻常的。我想说你的第一步是把它转换成一个普通的字符指针

2) 使用C风格字符串时,Printf是您最好的朋友

#include <stdio.h>
#include <string.h>

// Returns a newly allocated buffer containing string concatenated with the string representation of append_me
char * append (char * string, short int append_me)
{
  // Assume that the short int isn't more than 5 characters long (+1 for space, +1 for possible negative sign)
  char * result = new char[strlen(string) + 7];
  sprintf (result, "%s %hd", string, append_me);
  return result;
}

// Just a wrapper method to abstract away unsigned char * nonsense.
unsigned char * append (unsigned char * string, short int append_me)
{
  return (unsigned char *)append ((char *) string, append_me);
}

int main()
{
  // Not sure why we're using unsigned char, but okay...
  unsigned char * the_string = (unsigned char *)"Hello World!";

  the_string = append (the_string, 574);

  printf ("%s\n", the_string);

  // We're responsible for cleaning up the result of append!
  delete[] (the_string);

  return 0;
}
#包括
#包括
//返回一个新分配的缓冲区,其中包含与append\u me的字符串表示形式连接的字符串
char*append(char*string,短int-append_-me)
{
//假设短整数长度不超过5个字符(+1表示空格,+1表示可能的负号)
char*result=新字符[strlen(字符串)+7];
sprintf(结果,“%s%hd”,字符串,追加内容);
返回结果;
}
//只是一个包装器方法来抽象掉无符号的char*废话。
无符号字符*追加(无符号字符*字符串,短整数追加)
{
返回(unsigned char*)append((char*)字符串,append\u me);
}
int main()
{
//不知道为什么我们要用无符号字符,但好吧。。。
unsigned char*字符串=(unsigned char*)“Hello World!”;
_字符串=append(_字符串,574);
printf(“%s\n”,_字符串);
//我们负责清理附加的结果!
删除[](_字符串);
返回0;
}

如果您想将数字添加为string比如:string=“ala”和number=20,那么您希望得到result=“ala20”,而不是使用原始指针(在大多数情况下,对于C++来说,这是不必要的),您可以使用
std::stringstream
,它可以让您附加任何简单的类型(和字符串):

如果要序列化短到字符缓冲区(逐字节复制),可以使用
memcpy

memcpy(&buffer[offset], &value, sizeof(value));
当然,在
缓冲+偏移之后,您需要有足够的内存


你没有说,这次行动的目的是什么。如果它是为了显示目的(如第一个),那么
std::stringstream
就是最好的选择。如果您正在将一些数据保存到文件或通过套接字传递,则第二个版本的内存消耗较少-对于
short
(32767)的最大值,第一个版本将需要5B(位数-每位数1B),而第二个版本将保留2B上的任何short值(假设
short
大小为2B).

你到底想达到什么目的?我想在鼠标上加一个大象,我认为唯一能做的就是用割草机。”你的问题听起来就是这样:)我有一个预制作的无符号字符*用来保存数据。这是我从无法编辑的方法中获得的代码。我想在这个数据的末尾添加一个简短的int值。我没有代码可以显示,因为我不知道从哪里开始@Drax:我需要它作为一个无符号字符*如果你可以这样做,那么是:)@Dries指针只能保存的“数据”是一个地址。你的意思是它指向一个数组(数据)?如果是这样,你从分配额外的空间来添加短It的方法。我的经验法则是使用C字符串API和C++字符串C++来作为C++字符串。
I have 2 apples.
memcpy(&buffer[offset], &value, sizeof(value));