c - 使用指针模拟简单函数的引用传递,但没有输出

标签 c function pointers printf pass-by-reference

我引用了以下问题:

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

我正在尝试一个非常类似的练习,只不过我没有实现“交换”函数,而是尝试实现一个计算整数立方的函数。对我来说令人困惑的是我根本没有得到任何输出,甚至没有得到“hello world”测试输出。事实上我得到的只是以下内容:

process exited after 1.967 seconds with return value 3221225477

我的代码如下:

#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;
}

最佳答案

如果您使用指针模拟按引用传递,则必须将指针传递给函数,而不是变量。 *q = &x; 应为 q = &x; 并且函数调用应为 cube1(&x)cube1(q) .

但即使您这样做,您也会调用未定义的行为,因为您正在调用 cube1(&x),它会修改 x 并传递 x > 作为参数,中间没有序列点。不保证评估顺序。

例如在我的系统上它输出我:

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

为了避免这种情况,您应该在两个单独的语句中打印 x 和函数的返回值:

    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));

关于c - 使用指针模拟简单函数的引用传递,但没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52632009/

相关文章:

c - 为什么函数会被跳过而不被读取?

c++ - 'malloc' 和 'new' 是如何工作的?它们有何不同(实现方面)?

c - gwan -r 不读取最新文件

c - 扩展动态分配的指针数组

c++ - 载体如何清理自己? (或者他们呢?)

c - 在函数之间跳转或在函数之间传递值更好吗? C

javascript - 这两个函数的范围有什么区别

c - 不兼容的指针类型

c - 我正在学习 "Function callback"并且我的代码中出现了段错误?

C - 动态结构数组