I have this code..
#include <stdio.h>
#include <string.h>
int main() {
char a[6]="Hello";
char b[]="this is mine";
strcpy(a,b);
printf("%d\n",sizeof(a));
printf("%d\n",sizeof(b));
printf("%s\n",a);
printf("%s\n",b);
printf("%d\n",sizeof(a));
return 0;
}
6
13
this is mine
this is mine
6
I want to ask even I have copied the larger strng to a
but its size is not changing but its contents are changing why?
Any help would be appreciated..
The size is not changing because for the compiler the array
a
has a fixed size and you cannot change it and no one can.The contents are changing because there is no check performed for the bounds of the array, and it's working because of a coincidence. The code you posted has undefined behavior, and one of the possible outcomes is that it works as it is working in your case, but that will not necessarily always happen, add a variable to your
main()
function for example, and it might stop working.