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?
channelUrl
and deviceId
are pointers, so sizeof
just returns the size of a pointer, not the lengths of the strings. Use strlen()
.buffer
is uninitialized, so you can't concatenate to it.strcat()
, you can use sprintf()
.malloc()
.char* getSubscriberUrl(char* channelUrl, char* deviceId) {
char *buffer = malloc(strlen(channelUrl) + strlen(deviceId)+1);
sprintf(buffer, "%s%s", channelUrl, deviceId);
return buffer;
}