#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0

    Clearing value referenced, returning original value - C Language


    Hello,

    I'm a beginner programmer and I'm having some trouble understanding pointers in C (shocking, right?). I've come to an exercise that has left me a little baffled.

    The exercise is asking me to have the user assign some value to the variable "number" and use a function call to clear the value referenced by a pointer to it and also return the original value.

    Here's how it's supposed to go:

    Code:
    int number = 10;
    int oldNumber = clearAndReturnOld(&number);
    It is then passed to some function with this signature:
    Code:
    clearAndReturnOld(int* x)
    After the function runs, oldNumber should be 10 and number should be 0.

    Here was my first attempt; it returns the correct values, but they're assigned to the wrong things. I don't know how to correct this.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    clearAndReturnOld(int* x);
    
    int main(void)
    {	int number;
    	int oldNumber;
    	printf("Enter a value for number.\n");
    	scanf("%d", &number);
    	int oldNumber = clearAndReturnOld(&number);
    	printf("The values of the oldNumber and number are %d and %d", oldNumber, number);
    	return EXIT_SUCCESS;
    
    }
    
    clearAndReturnOld(int* x)
    {
    	return *x -*x;
    }
    Any help/insight would be much appreciated, thanks for your time. :)
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2009
    Posts
    149
    Rep Power
    37
    Originally Posted by mintyfresh
    Code:
    	return *x -*x;
    This should return 0. You say it is returning the right "values", but it returns 0 and if what you're looking for is to return the old value of the number you passed in this does not do that.

    You do need to dereference the pointer you've passsed into clearAndReturnOld:

    1) assign its dereferenced value to a local variable (of type int) inside clearAndReturnOld

    2) assign 0 to the dereferenced pointer and return the value of your local variable.

    * is the dereference operator. *x - *x means the value that x points to - the value that x points to which is 0 all day every day to my knowledge. *x = 0 means assign 0 to the location x points to, a = *x means assign the value that x points to to the variable a.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0
    Wow, that makes so much more sense now! I didn't understand the idea of dereferencing all too well, as you probably noticed. Thanks for such a clear explanation-- the program runs perfectly now. :D

IMN logo majestic logo threadwatch logo seochat tools logo