user3629146
user3629146

Reputation: 107

Pointer returning memory address?

I'm working with the program that scans a number in the main program. After that this program calls for a function change_number(), and as an argument gives the numbers memory address. After this program should add 3 to the number in the sub-program, print it out in the subprogram and restore that new value. However, when trying to print the number out in the subprogram change_number(), it prints out it's memory address. My understanding is that a program should return integers value when referring to the pointer with * -notation or just by inserting a variables name. Another compiler which i have tried says the following error message, and does not even compile, either with x -notation or with *pointer_x -notation:

I don't understand because my pointer is introduced as an integer, just like the integer itself. Here is the code:

#include<stdio.h>

void change_number(int *x);

int main()
{

    int x;
    printf("Give number x: ");
    scanf("%d", &x);
    printf("In main program: x = %d\n", x);
    change_number(&x);
    printf("In main program: x = %d\n", x);

    return 0;

}

void change_number(int *x)
{

int *pointer_x;
pointer_x = &x;
x = x + 3;
printf("In sub program: x = %d\n", *pointer_x);

}

Upvotes: 2

Views: 4858

Answers (3)

Ben Cottrell
Ben Cottrell

Reputation: 6110

The code you've pasted should fail to compile on the line pointer_x = &x; as both x and pointer_x are type int*

Using the address-of operator on a pointer variable gives you a pointer-to-pointer - in this case, &x yields a type of int**

In addition, the line x = x + 3 advances a pointer location in memory by 3*sizeof(int) bytes, it's not modifying the original int variable.

Perhaps you intended to write *x = *x + 3 instead?

void change_number(int *x)
{
    int *pointer_x;
    pointer_x = x;
    *x = *x + 3;
    printf("In sub program: x = %d\n", *pointer_x);
}

Upvotes: 1

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

When you write void change_number(int *x), x is received as an int *. So, x points to int and *x is int.

So you'll need to change the following:

pointer_x = x;
*x = *x + 3;
printf("In sub program: x = %d\n", *pointer_x);

Now this prints correctly. But to restore the value, just add this line at the end:

*x = *x - 3;

Upvotes: 0

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

The parameter x already contains address of the variable x from main so it have to be written as

void change_number(int *x)
{

  int *pointer_x;
  pointer_x = x;
  *x = *x + 3;
  printf("In sub program: x = %d\n", *pointer_x);

}

Upvotes: 0

Related Questions