我有个家庭作业问题:
A部分
编写一个C程序,测试下列数据类型是否通过引用或值传递,并将其发现的内容打印到终端:
假设,如果您的程序发现int是通过值传递的,而int的数组是通过值传递的,那么它应该产生输出,如: int: pass- by值数组:pass- by值。
我明白,但我不明白的是:
编辑:如果有人用一个具体的例子向我解释了这一点,比如:假设我有一个长度为10 int的数组存储在内存位置0(是的,我知道,不是真实的生活,而是为了这个例子.)。如果该数组是通过引用传递的,它会是什么样子?如果它是通过值传递的,它会是什么样子?
发布于 2012-06-22 15:05:30
是按值传递还是通过引用传递?
当您说“将数组传递给函数”时,指向第一个元素的指针实际上会传递给函数。这允许被调用的函数修改数组的内容。由于没有生成数组的副本,所以可以说数组是通过引用传递的。
提示我如何做到这一点?
试验应是:
main()中创建一个本地数组。main()中,再次打印本地数组的内容6和7中匹配。你有证据。如何按值传递数组?
通过值传递数组的唯一可能方法是将数组包装在结构中。
在线样本:
#include <iostream>
struct myArrayWrapper
{
int m_array[5];
};
void doSomething(myArrayWrapper a)
{
int* A = a.m_array;
//Display array contents
std::cout<<"\nIn Function Before Modification\n";
for (size_t j = 0; j < 5; ++j)
std::cout << ' ' << A[j];
std::cout << std::endl;
//Modify the array
for (size_t j = 0; j < 5; ++j)
A[j] = 100;
std::cout<<"\nIn Function After Modification\n";
//Display array contents
for (size_t j = 0; j < 5; ++j)
std::cout << ' ' << A[j];
std::cout << std::endl;
}
int main()
{
myArrayWrapper obj;
obj.m_array[0] = 0;
obj.m_array[1] = 1;
obj.m_array[2] = 2;
obj.m_array[3] = 3;
obj.m_array[4] = 4;
doSomething(obj);
//Display array contents
std::cout<<"\nIn Main\n";
for (size_t j = 0; j < 5; ++j)
std::cout << ' ' << obj.m_array[j];
std::cout << std::endl;
return 0;
}输出:
In Function Before Modification
0 1 2 3 4
In Function After Modification
100 100 100 100 100
In Main
0 1 2 3 4发布于 2012-06-22 15:06:18
C只按值将参数传递给函数。
来自强大的Kernighan & Ritchie,第二版:
(1.8,按值调用)“在C中,所有函数参数都由"value”传递
https://stackoverflow.com/questions/11158858
复制相似问题