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:
channelUrl
anddeviceId
are pointers, sosizeof
just returns the size of a pointer, not the lengths of the strings. Usestrlen()
.- You only need to add 1 -- there's only 1 null terminator needed for the combined string.
buffer
is uninitialized, so you can't concatenate to it.- Instead of using multiple calls to
strcat()
, you can usesprintf()
. - 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;
}