1,105,546 Community Members

pointer problem

Member Avatar
aswekown
Newbie Poster
7 posts since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 3 [?]
Skill Endorsements: 0 [?]
 
0
 

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?

Member Avatar
deceptikon
Eternally Awesome
4,693 posts since Jan 2012
Reputation Points: 1,341 [?]
Q&As Helped to Solve: 689 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
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?

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.

Member Avatar
andrag73
Newbie Poster
6 posts since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

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 !

Question Answered as of 1 Year Ago by deceptikon and andrag73
Member Avatar
deceptikon
Eternally Awesome
4,693 posts since Jan 2012
Reputation Points: 1,341 [?]
Q&As Helped to Solve: 689 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
0
 

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;
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article