gpt4 book ai didi

c - 编译器如何理解给定函数是按值传递还是按引用传递?

转载 作者:行者123 更新时间:2023-11-30 21:03:22 24 4
gpt4 key购买 nike

C 编译器如何理解给定函数是按值传递还是按引用传递?如果变量的指针作为整数(按值传递)传递给函数会发生什么?或者这在 C 中可能吗?

即:将一个变量的地址复制到另一个变量(int),并将该变量传递给函数。这里被调用的函数将获得一个地址作为普通的整数参数。这在C语言中可能吗?如果不是为什么?

最佳答案

在 C 中,只能按值传递(仅在 C++ 中支持按引用传递)。

标准变量和指针变量都是按值传递的。因此,编译器不得对引用或值进行任何检查。

标准变量和指针变量是一样的,都存储值,但是指针变量只能存储地址值,并且支持解引用运算符“*”,该运算符获取指针变量指向的值。

因此,当您按值传递(C 仅支持按值)指针变量时,指针变量的值将被复制到本地指针变量(在函数堆栈中实例化)中,该变量是功能。因此,您可以使用解引用运算符访问复制到本地指针变量中的地址值。

添加评论 2014 年 8 月 22 日

我可以用一个例子更好地解释:

void FuncSet10(int* PtrArgument)
{
// The PtrArgument is a local pointer variable
// it is allocated in the stack. The compiler
// copies the MyIntVariable address in this variable

// Using dereferencing operator I can access to
// memory location pointed by PtrArgument
*PtrArgument = 10;


}

void FuncSet20(int IntArgument)
{
// The IntArgument is a local variable
// allocated in the stack. The compiler
// copies the MyIntVariable address in this variable

// this code emulates the dereferencing operator
// and so poiter mechanism.
*((int*)IntArgument) = 20;
}

void FuncMovePointer(int* pointer)
{
int a = *pointer++; // now a contains 1
int b = *pointer++; // now b contains 2
int c = *pointer++; // now c contains 3

printf("a contains %d\n", a);
printf("b contains %d\n", b);
printf("c contains %d\n", c);

// The *Ptr now points to fourth (value 4) element of the Array
printf("pointer points to %d\n", *pointer);
}


int _tmain(int argc, _TCHAR* argv[])
{

int Array[] = {1, 2, 3, 4}; // Array definition
int* pointer = Array; // pointer points to the array

int MyIntVariable;

// First example for explanation of
// the pointer mechanism and compiler actions

// After calling this function MyIntVariable contains 10
FuncSet10(&MyIntVariable);

printf("MyIntVariable contains %d\n", MyIntVariable);

// After calling this function MyIntVariable contains 20
// This code emulate pointer mechanism
FuncSet20((int)&MyIntVariable);

printf("MyIntVariable contains %d\n", MyIntVariable);

// Second example to demonstrate that a pointer
// is only a local copy in a called function

// Inside function the pointer is incremented with ++ operator
// so it will point the next element before returning by function
// (it should be 4)
FuncMovePointer(pointer);

// But this is not true, it points always first element! Why?
// Because the FuncMovePointer manages a its local copy!

printf("but externally the FuncMovePointer it still points to first element %d\n", *pointer);

return 0;
}

希望上面的代码可以帮助您更好地理解。

安杰洛

关于c - 编译器如何理解给定函数是按值传递还是按引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25398676/

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