Please explain me what is error in my programm ?

Discussion in 'Programmer's Corner' started by Shivanshu j'Mishra, Aug 20, 2013.

  1. Shivanshu j'Mishra

    Thread Starter New Member

    Aug 20, 2013
    int main()
    int i, n;
    char *x = "girl";
    n = strlen(x);
    *x = x[n];
    for(i=0; i<n ,i++)
    return 0;
  2. sirch2

    Senior Member

    Jan 21, 2013
    Does the compiler report an error? If so what is the error, does it give a line number?

    I've spotted one issue

    for(i=0; i<n ,i++)

    should be

    for(i=0; i<n; i++)
  3. joeyd999

    AAC Fanatic!

    Jun 6, 2011
    Code ( (Unknown Language)):
    2. n = strlen(x);
    3. *x = x[n];
    This will set the first character of the string to 0, changing the length of the string to 0. Printf will then print the null string -- which is nothing.
    ErnieM likes this.
  4. WBahn


    Mar 31, 2012
    First, use CODE tags to make your code much more readable:

    Second, your post is like going to a doctor's office and say, "Can you tell me what's wrong with me?" or going taking your car to a mechanic and saying, "Can you tell me what is wrong with my car?"

    The fact that you are asking means that you have some REASON to believe that something is wrong in the first place. Why not share that with those you are asking for help?

    What is it doing that it shouldn't?

    What error messages or warnings is it giving?

    What is it not doing that it should?

    What is it that you WANT it to do in the first place?

    This last one is really important. We've had people that have posted code that was perfectly valid and reasonable only to eventually find out that the person was trying to do something completely different.

    So it might go like something like this:

    This program should produce the following output:

    But it is producing this, instead:

    It compiles, but I get a warning that says this:
    tshuck likes this.
  5. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    Agree... though it took me a bit to see why it is so.

    Don't forget that in C an array is always based off zero, so an array F with 3 elements is located at:

    F[0], F[1] and F[2]

    By adding the length of the string to the pointer (what x[n]) does) you wind up pointing just past the end of the string as the last character is at [n-1].
  6. WBahn


    Mar 31, 2012
    And, for completeness, in C strings are NUL-terminated, meaning that the character immediately after the last character is a zero (the NUL character). C uses this to detect the end of the string, so setting the first character to NUL means that C will interpret it as an empty string.
    ErnieM likes this.