Reputation: 89
Folks, I have basic and simple question on pointers. The below is code is giving a segmentation fault.
int main()
{
char *str = "hello, world\n";
char *strc = "good morning\n";
strcpy(strc, str);
printf("%s\n", strc);
return 0;
}
Can't we copy from pointer to other.
Upvotes: 1
Views: 696
Reputation: 310950
You may not change string literals. It is what you are trying to do in statement
strcpy(strc, str);
that is you are trying to overwrite string literal "good morning\n" pointed to by pointer strc
.
Of cource you may use pointers in function strcpy. The valid code can look like
#include <stdio.h>
#include <string.h>
int main()
{
char *str = "hello, world\n";
char strc[] = "good morning\n";
strcpy(strc, str);
printf("%s\n", strc);
return 0;
}
Or
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str = "hello, world\n";
char *strc = malloc( 14 * sizeof( char ) );
strcpy( strc, "good morning\n" );
//...
strcpy(strc, str);
printf("%s\n", strc);
free( strc );
return 0;
}
Upvotes: 2