Reshmi khanna
Reshmi khanna

Reputation: 89

Copying the string of pointer to other pointer

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.

  1. if i have char *strc = "good morning\n", can't i do like this strc[5] = '.';. Why this also giving a seg fault.

Upvotes: 1

Views: 696

Answers (1)

Vlad from Moscow
Vlad from Moscow

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

Related Questions