There's no solution to your problem. You ask for something like a vector, but vectors only know their size because they store it. Since it seems you aren't allowed to change the signature of your function then a loop is your only alternative. In any case it doesn't seem that inefficient to me.
Your code does have bugs, when you are calculating the size of buff1 you adjust the buff1 pointer, so that is no longer points to the start of the block when you do the copy. You need to substract the size of the buffer before you copy. Also you seem to be assuming that your two input buffers are the same size.
This would seem to be a better version of your code.
char* func(char *buff1, char *buff2, char *outbuff)
{
int size1 = 0;
while (*buff1 != '\0')
{
size1++;
buff1++;
}
int size2 = 0;
while (*buff2 != '\0')
{
size2++;
buff2++;
}
memcpy(outbuff, buff1 - size1, sizeof(char)*size1);
memcpy(outbuff + size1, buff2 - size2, sizeof(char)*size2);
return outbuff;
}
You could use strlen which does the same thing as the code above, but strlen is a loop as well. So the advantage of using strlen is not that you are avoiding a loop, only that the code is a little easier to understand.
#include <cstring>
char* func(char *buff1, char *buff2, char *outbuff)
{
int size1 = strlen(buff1);
int size2 = strlen(buff2);
memcpy(outbuff, buff1, sizeof(char)*size1);
memcpy(outbuff + size1, buff2, sizeof(char)*size2);
return outbuff;
}
Then finally you could use strcpy and strcat, which also have similar effect
#include <cstring>
char* func(char *buff1, char *buff2, char *outbuff)
{
strcpy(outbuff, buff1);
strcat(outbuff, buff2);
return outbuff;
}
This apparently avoids any loops and size calculations at all. But of course they are still happening, just internally to the strcpy and strcat functions.
There is one difference between this latest version and the two previous versions. The version with strcpy and strcat also copies the terminating '\0' character to outbuff, so outbuff will be null temrinated just ilke you are assuming that buff1 abd buff2 are. This seems like an advantage to me, but you might not agree.
func.buff1points to after thewhileloop?