首页 > 解决方案 > using pointers to emulate pass by reference with simple function but getting no output

问题描述

I have referenced the following question:

Using pointers to emulate Pass-by-Reference in a Pass-by-Value function (C and C++)

I am attempting a very similar exercise except instead of implementing a 'swap' function, I'm attempting to implement a function that calculates the cube of an integer number. The perplexing thing for me is I get no output at all, not even the "hello world" test output. In fact all I get is the following:

process exited after 1.967 seconds with return value 3221225477

My code is as follows:

#include <stdio.h>
#include <stdlib.h>

int cube1(int *p);
int cube2(int a);

int main(int argc, char *argv[]) 
{
int x;
int *q;

x = 3;
*q = &x;

//output test  
printf("hello world\n");

printf( "x = %d\n", x );    
printf( "q = %p\n", q );

printf("%d cubed using variable passing by reference =  %d\n", x, cube1(x));
printf("%d cubed using  variable passing by value =  %d\n", x, cube2(x));

system("pause");
return 0;
}

//simulated pass by reference
int cube1(int *p)
{
int temp = *p; 
temp = temp*temp*temp;
*p = temp;

return *p;
}

//standard pass by value
int cube2(int a)
{
    return a*a*a;
}

标签: cfunctionpointersprintfpass-by-reference

解决方案


If you emulate pass by reference with pointers you have to pass the pointer to the function, not the variable. *q = &x; should be q = &x; and the function call should be cube1(&x) or cube1(q).

But even if you do that you would invoke undefined behavior since you are calling cube1(&x), which modify x, and pass x as parameter without a sequence point in between. There is no guaranteed order of evaluation.

For example on my system it outputs me:

27 cubed using variable passing by reference =  27
27 cubed using  variable passing by value =  19683

To avoid this you should print x and the return value of the function in two seperate statements:

    printf("%d cubed using variable passing by reference =  ", x);
    printf("%d\n", cube1(&x));
    printf("%d cubed using  variable passing by value =  %d\n", x, cube2(x));

推荐阅读