Let's take an example.
#include <stdio.h>
#include <string.h>
int main() {
char str1[7] = "hello ";
printf("Initial size of str1 is: %d\n", strlen(str1));
char str2[] = "buddy";
printf("%s\n", strcat(str1, str2));
printf("Final size: %d\n", strlen(str1));
}
The output of the above program will be
Initial size of str1 is: 6
hello buddy
Final size: 11
--------------------------------
Process exited after 0.835 seconds with return value 0
Press any key to continue . . .
See? how the size of str1
changed from 7 to 11 (including null variable), regarding that what I think would have happened is :
- Some function I do not know may have reallocated contiguous memory for
str1
starting from same address as before i.estr1
with sizestrlen(str1)+strlen(str2)+1
+1 for null value, and then redefined it to get hello buddy.
If I am wrong please tell, if not then, what function is it and how does it work?
One more question: how can I write a code to do the above task without the use of strcat
function.
I tried doing it using realloc()
but didn't quite succeed may be that's because realloc()
can only reallocate dynamically allocated memory, is it so?