简体   繁体   English

无法将两个 char* 合并为一个

[英]unable to concatinate two char* into one

I'm having trouble with creating a function that receives 2 char* and need to return a char* that concatenate the input strings.我在创建接收 2 char* 并且需要返回连接输入字符串的 char* 的 function 时遇到问题。

char* deviceId = "A1B2C3D4";
char* channelUrl = "/arduino/subscribers/";


char* getSubscriberUrl(char* channelUrl, char* deviceId) {
  char* buffer[sizeof(channelUrl) + sizeof(deviceId)+2];
  strcat(buffer, channelUrl);
  strcat(buffer, deviceId);

  return buffer;
}

I'm getting this error:我收到此错误:

initializing argument 1 of 'char* strcat(char*, const char*)'
 char  *strcat (char *__restrict, const char *__restrict);
                ^~~~~~
sketch_sep13a:87:10: error: cannot convert 'char**' to 'char*' in return
   return buffer;

What did I do wrong?我做错了什么?

  1. channelUrl and deviceId are pointers, so sizeof just returns the size of a pointer, not the lengths of the strings. channelUrldeviceId是指针,所以sizeof只返回指针的大小,而不是字符串的长度。 Use strlen() .使用strlen()
  2. You only need to add 1 -- there's only 1 null terminator needed for the combined string.您只需要添加 1 - 组合字符串只需要 1 个 null 终止符。
  3. buffer is uninitialized, so you can't concatenate to it. buffer未初始化,因此您无法连接到它。
  4. Instead of using multiple calls to strcat() , you can use sprintf() .您可以使用sprintf() strcat() ) 。
  5. You can't return a local array.您不能返回本地数组。 You need to allocate the result with malloc() .您需要使用malloc()分配结果。
char* getSubscriberUrl(char* channelUrl, char* deviceId) {
  char *buffer = malloc(strlen(channelUrl) + strlen(deviceId)+1);
  sprintf(buffer, "%s%s", channelUrl, deviceId);

  return buffer;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM