Thread: Need Help!!! Can anyone explain

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    7

    Question Need Help!!! Can anyone explain

    3. #include <stdio.h>
    main()
    {
    char a[20]="Richard";
    char *b="Jack";

    char *ptr1=a;
    char *ptr2=b;

    *ptr1=*ptr2;
    ptr1++; ptr2++;

    *ptr1=*ptr2;
    ptr1++; ptr2++;

    printf("%s",a);

    }


    This code runs fine whereas the following code gives a segmentation fault. Can anyone explain why.

    #include <stdio.h>
    main()
    {
    char *a="Richard";
    char *b="Jack";

    char *ptr1=a;
    char *ptr2=b;

    *ptr1=*ptr2;
    ptr1++; ptr2++;

    *ptr1=*ptr2;
    ptr1++; ptr2++;

    printf("%s",a);

    }


    Thanks..Jack

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    In the second example, 'a' is a string literal, which cannot be changed. The first example works because 'a' is an array who's contents have been initialized.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you explain these bitwise operations?
    By 6tr6tr in forum C++ Programming
    Replies: 6
    Last Post: 10-29-2008, 01:19 PM
  2. Please explain?
    By neo_phyte in forum C Programming
    Replies: 3
    Last Post: 08-25-2006, 05:23 AM
  3. Can someone explain to me what this code means
    By Shadow12345 in forum C++ Programming
    Replies: 3
    Last Post: 12-22-2002, 12:36 PM
  4. Replies: 4
    Last Post: 11-19-2002, 09:18 PM
  5. Can someone explain "extern" to me?
    By valar_king in forum C++ Programming
    Replies: 3
    Last Post: 09-16-2001, 12:22 AM