gpt4 book ai didi

c - C中的指针传递/引用传递

转载 作者:太空宇宙 更新时间:2023-11-04 07:22:36 24 4
gpt4 key购买 nike

我知道如何在函数中传递指针,我觉得我仍然混淆两个术语,例如按引用传递和按指针传递。

有人问我:

Write a program that uses pointers to pass a variable x by reference to a function where its value is doubled. The return type of the function should be void. The value of the variable should be printed from main() after the function call. The original value of x is 5.

我写了下面的代码。能否根据问题的需求告诉我哪个评论号是对的,解开我的疑惑?

#include <stdio.h>
//double pointer
//void double_ptr(int **x_ptr)
//{
// **x_ptr *=2;

//}

void double_ptr(int *x_ptr)
{
*x_ptr *=2;
}


int main()
{
int x=5;
int *x_ptr=&x; // single pointer

//double_ptr(*x_ptr); // this is out of question's demand.
//int**x_x_ptr=&x_ptr; // double pointer
//double_ptr(&x_ptr); // 1. pass with double pointer
//double_ptr(x_x_ptr); //2. pass with double pointer
//printf("%d",**x_x_ptr); //3.print with double pointer

double_ptr(x_ptr); //4.pass by pointer?
//double_ptr(&x); //5.pass by reference?
printf("%d",*x_ptr);
return 0;
}

最佳答案

指针传递实际上是值传递,C中没有引用传递这种概念。

在 C 中,通过引用传递 == 通过指针传递。

void double_ptr(int *x_ptr)
{
*x_ptr *=2;
}
int main()
{
int x=5;
double_ptr(&x); /* a value is being passed*/
}

按引用传递(在 C++ 中):

void double_ptr(int& x_ptr)
{
x_ptr *=2;
}
int main()
{
int x=5;
int &x_ptr=x;
double_ptr(x_ptr); /* no temporary is being created i.e. no extra memory allocation is here*?
}

关于c - C中的指针传递/引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20443699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com