Home > Software engineering >  unable to concatinate two char* into one
unable to concatinate two char* into one

Time:09-15

I'm having trouble with creating a function that receives 2 char* and need to return a char* that concatenate the input strings.

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?

CodePudding user response:

  1. channelUrl and deviceId are pointers, so sizeof just returns the size of a pointer, not the lengths of the strings. Use strlen().
  2. You only need to add 1 -- there's only 1 null terminator needed for the combined string.
  3. buffer is uninitialized, so you can't concatenate to it.
  4. Instead of using multiple calls to strcat(), you can use sprintf().
  5. You can't return a local array. You need to allocate the result with malloc().
char* getSubscriberUrl(char* channelUrl, char* deviceId) {
  char *buffer = malloc(strlen(channelUrl)   strlen(deviceId) 1);
  sprintf(buffer, "%s%s", channelUrl, deviceId);

  return buffer;
}
  • Related