Hi, I have a piece of code here.

#include <stdio.h>
int main()
{   

    // jimmy and masked_raider are just aliases for the same memory address. They’re pointing to the same place

    char masked_raider[] = "Alive";
    char *jimmy = masked_raider; 
    printf("Masked raider is %s, Jimmy is %s\n", masked_raider, jimmy);
    masked_raider[0] = 'D';
    masked_raider[1] = 'E';
    masked_raider[2] = 'A';
    masked_raider[3] = 'D';
    masked_raider[4] = '!';
    printf("Masked raider is %s, Jimmy is %s\n", masked_raider, jimmy);
    jimmy[0] = 'N';
    jimmy[1] = 'O';
    jimmy[2] = '\0';
    printf("Masked raider is %s, Jimmy is %s\n", masked_raider, jimmy);
    jimmy = "not ok";  
    printf("Masked raider is %s, Jimmy is %s\n", masked_raider, jimmy);
    return 0;
}

My problem is after change the value of Masked raider the jimmy changed,but when set jimmy = "not ok";
Masked raider did not change,how to explain it?

My problem is after change the value of Masked raider the jimmy changed,but when set jimmy = "not ok";
Masked raider did not change,how to explain it?

When you changed jimmy to "not ok", you pointed it to a different object (the string literal "not ok"). At that point, jimmy no longer aliases masked_raider.

deceptikon, Yes !

jimmy = "not ok"; compiles as new memory area ("not ok\0") with no changes in masked_raider array area !

If you do:

masked_raider = jimmy;

You will see the change you ask !

If you do:
masked_raider = jimmy;
You will see the change you ask !

Um, no. That won't compile because masked_raider is an array; it doesn't support direct assignment. The only way to restore the alias is to assign the address of the first element of masked_raider to jimmy (which may be what you really meant, but accidentally reversed the assignment):

/* Option 1: Implicit conversion to a pointer */
jimmy = masked_raider;

/* Option 2: Explicit conversion to a pointer */
jimmy = &masked_raider[0];

/* Option 3: Weird stuff (not recommended) */
jimmy = &*masked_raider;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.