I've encountered something in a simple code test that started bothering me. I don't really understand the reason the program crashes before line with the strcpy function invocation.
So basically, can someone explain to me, why does this sample of code works correctly:
#include <stdio.h>
#include <string.h>
#define WORD ", sugar."
#define SIZE 40
int main(void){
const char * source = WORD;
char copy_of_arr[SIZE] = "Try me on the ring, brother.";
char * w1;
puts(source);
puts(copy_of_arr);
w1 = strcpy(copy_of_arr + 6, source);
puts(copy_of_arr);
puts(w1);
return 0;
}
Result:
, sugar.
Try me on the ring, brother.
Try me, sugar.
, sugar.
> End
And this does not?:
#include <stdio.h>
#include <string.h>
#define WORD ", sugar."
int main(void){
const char * source = WORD;
char * copy_of_arr = "Try me on the ring, brother.";
char * w1;
puts(source);
puts(copy_of_arr);
w1 = strcpy(copy_of_arr + 6, source);
puts(copy_of_arr);
puts(w1);
return 0;
}
Result:
, sugar.
Try me on the ring, brother.
> End
I think I don't understand the concept of C strings correctly. I know, that strcpy function needs to copy source with type const char * to type char*, but why it does not copy in the second sample (and crashes instead) if char copy_of_arr[SIZE] and char * copy_of_arr should be the same type?