C:多个字符串的字符串连接截断连接后的字符串部分

C : string concatenation of multiple string truncates the portion of string after concatenation

我必须使用 snprintf 将多个字符串连接成一个字符串,

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

int main()
{
  char id[] =  "D0D0-0000-0000-0000-0001-A431";
  char mac[] = "fc017c0f2b75";
  char aid[] = "1";

  printf("size of id :: %ld\n", sizeof(id));
  printf("size of mac :: %ld\n", sizeof(mac));
  printf("size of aid :: %ld\n", sizeof(aid));

  char *uniqueID = (char*)malloc(50);
  snprintf(uniqueID, sizeof(uniqueID), "%s.%s.%s", id, mac, aid);
  printf("uniqueID :: %s\n", uniqueID);
  printf("size of uniqueID :: %ld\n", sizeof(uniqueID));
}

对于使用上述代码的给定要求,我可以产生以下结果,

size of id :: 30
size of mac :: 13
size of aid :: 2
uniqueID :: D0D0-00
size of uniqueID :: 8

然而,所需的结果是,

size of uniqueID :: D0D0-0000-0000-0000-0001-A431.fc017c0f2b75.1

这里有什么问题?如何解决?

您为 snprintf 提供的大小不正确(sizeof(uniqueID) 是指针的大小 = 8)。对于您的情况,应该是:

  snprintf(uniqueID, 50, "%s.%s.%s", id, mac, aid);

如果 uniqueID 是一个数组,如下所示,您的程序会正常运行(sizeof(uniqueID) 是 char 数组的大小 = 50):

  char uniqueID[50] = {};
  snprintf(uniqueID, sizeof(uniqueID), "%s.%s.%s", id, mac, aid);