Total Pageviews

Tuesday, December 13, 2011

C loves me...C loves me not...

#include<stdio.h>
#include<string.h>

int main()
{
    int i, n;
    char *x="Alice";
    n = strlen(x);
    *x = x[n];
    for(i=0; i<=n; i++)
    {
        printf("%s ", x);
        x++;
    }
    return 0;
}

Hi C programmers, the output of the above program should have been: lice ice ce e
but when compiled it gives the output as follows : Alice lice ice ce e

Could someone please explain?

3 comments:

  1. Don't know what compiler you are using, but i am getting a segfault in line 9 using gcc in Ubuntu

    *x= x[n];

    ReplyDelete
  2. well...actually the problem can be broken down to this program...and its not giving any error in codepad.org..try this...
    #include
    main()
    { char *p,*q;
    char s[] = "good";
    q =s;
    *q = 'a';
    p = "good";
    *p = 'a';
    printf("%s %s",p,s);
    }
    both p and q are pointers to the first character of the string "good" and both are trying to change the first character to a but only the one who is using the string is able to...!!

    ReplyDelete
    Replies
    1. When you write p="good"; statement, the memory to "good" string literal is allocated in different segment(which is read-only) this is why when you try to change its value, it gives runtime error in most compilers. And this is the reason why value is not changed in codepad and it gives exit_failure which is a type of runtime error.

      Delete