c - 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;
}
解决方案
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));
推荐阅读
- python - python中对象的方法和属性有什么区别?
- java - 如何在Spring中通过ApplicationContext即时直接使用bean
- amazon-web-services - AWS EC2 phpMyAdmin 在允许 httpd.conf 文件中的 html 目录权限后停止工作
- node.js - forEach 中的 forEach 打印 nodejs mongodb 中 else 语句的双重结果
- db2 - 如何在 db2 中显示隐藏表?表已成功创建,但未显示在数据库中
- amazon-web-services - aws ecr get-login --region us-east-1 命令失败。
- unix - 如何从列到行获取唯一值
- angular - PrimeNg V.7 FullCalendar View Crash
- android - 此应用将受到管理 SMS 和 CALL_LOG 权限使用的 Google Play 政策变更的影响
- node.js - 有没有办法在 Xamarin 表单中使用使用 Nodejs 构建的 API,用于从 mongodb 更新、写入和获取数据到应用程序,反之亦然?