Thread: Question about pointers

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    2

    Question about pointers

    What follows is a very simple test to improve my understanding of C pointers. I have two pointers. The first pointer is assigned the value "Hello". Then the second pointer is set to the first pointer. Correct me if I am wrong, but now both pointers should point to the same string? Anyways, I change the contents of firstString to be "Goodbye". When I print out what both pointers are pointing to, I get "Hello" and "Goodbye". I don't understand how this is possible.

    Code:
    int main(int argc, char **argv)
    {
    	char* firstString;
    	char* newString;
    
    	firstString = "Hello";
    
    	newString = firstString;
    
    	firstString = "Goodbye";
    
    	printf("The memory location pointed to by firstString is: %d\n", firstString);
    	printf("The memory location pointed to by newString is: %d\n", newString);
    	
    	printf("\n%s",newString);
    	printf("\n%s",firstString);
    
    	getchar();
    
    	return 0;
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You are assigning the address of a string literal to the first pointer. Then you assign that value (that address) to the second pointer. Then you make the first pointer point to a different string literal. The second pointers till holds a different value. It's the same as doing this:
    Code:
    int x = 5, y = x;
    x = 3;
    x is five, and y is five, then set x to three.

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

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    newString is not pointing to firstString (you would need a char ** for that, since you would be pointing to a char *). It's pointing to what firstString was pointing to. If it helps, think of newString = firstString as copying the address stored in firstString into newString. Then you copy a new address (of "Goodbye") into firstString. newString doesn't automatically update.

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    2
    Thank you, now I understand.

    When I change firstString to "Goodbye". I'm actually pointing to a new place, not changing the data that is in the current place.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  2. Pointers to pointers question
    By mikahell in forum C++ Programming
    Replies: 10
    Last Post: 07-22-2006, 12:54 PM
  3. question about pointers
    By hoangvo in forum C++ Programming
    Replies: 4
    Last Post: 07-25-2005, 12:06 PM
  4. Question about pointers
    By maxhavoc in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2004, 12:46 AM
  5. Pointers Question.....Null Pointers!!!!
    By incognito in forum C++ Programming
    Replies: 5
    Last Post: 12-28-2001, 11:13 PM