【问题标题】:Passing variables to a function: scope and when to use & and *?将变量传递给函数:范围以及何时使用 & 和 *?
【发布时间】:2012-01-21 13:28:31
【问题描述】:
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "stdlib.h"

void test (int a,int *b, int result[], int serie[]);

int main()
{
    int *serie = malloc(sizeof(int));
    int result[20], a,b, i;
    a=0;
    b=0;

    for (i = 0; i < 20; i++) {
        result[i]=i+10;
        serie[i]=rand();
        printf("result is %d \n",result[i]);
    }

    test(a,&b,result,serie);
    printf("value of a inside main %d \n",a);
    printf("value of b inside main %d \n",b);

    for (i = 0; i < 20; i++) {
        printf("value of result inside main is %d and of serie is %d        \n",result[i],serie[i]);
    }

    getchar();
    return 0;
}

void test(int a, int *b, int result[], int serie[]) {
    int i;
    a=13;
    *b=14;
    printf("value of a inside the function %d \n",a);
    printf("value of b inside the function %d \n",*b);
    for (i = 0; i < 20; i++) {
        result[i]=result[i]*2;
        serie[i]=7;
        printf("value of result inside the function is %d and of serie is %d\n",result[i],serie[i]);
    }
}

基本上,这些代码所做的只是查看变量的范围,我写它是为了帮助自己,我想用一个函数来改变main 内的整数值(参见int b)你必须调用它使用&amp;b (test(a,&amp;b,result,serie);),然后在函数*b 中。所以我正在尝试对数组进行这种操作 &* 但它们不起作用。

看来你所要做的就是写数组void test(... int result[],int serie[]) 并调用函数只需将名称放在不带括号的位置:test(...,result,serie); 我说的对吗?

如果我只想更改函数内部的数组,比如使用变量 a,该怎么办?

【问题讨论】:

标签: c function scope


【解决方案1】:

是的,没错。为了修改数组,您只需将其声明为:

void test(... int result[], int serie[]);

或者这个:

void test(... int *result, int *serie);

以上两者是等价的。

为什么会这样是因为你传入了一个指针,它按值传递。这与数组本身不同,数组本身是通过引用传递(通过指针)。所以指针被复制了,如果你试图在不使用* 的情况下实际更改结果的值,它不会持续到函数之外。如果您想修改函数内部的数组而不修改原始数组,则必须在传入之前或之后复制它们。

【讨论】:

  • 我不确定如果我理解了你,我相信我自己的想法你所说的是普通变量(不是数组)需要一个指针来传递值,但数组本身是像指针一样,通过引用传递,所以你不需要创建另一个指向数组的指针?
  • @user1094566:有点。数组不是指针,但在大多数情况下,数组类型的表达式将被替换为指针类型的表达式,其值是数组中第一个元素的地址。 IOW,当你在main中调用test时,参数resultint的20元素数组转换为指向int的指针,其值为test[0]的地址。
【解决方案2】:

在 C 中,数组总是通过引用传递,因此将整数数组的地址传递给函数(例如,main 中的 &amp;result)就像传递双指针(int**)。您在尝试此操作时收到的错误是输入错误。

如果我只想像使用变量 a 一样更改函数内部的数组怎么办?

我不确定你这个问题是什么意思。你能澄清一下吗?

【讨论】:

  • Dan Fergo 明白,“如果您想修改函数内部的数组而不修改原始数组,则必须在传入之前或之后复制它们。”这就是我的意思。
【解决方案3】:

不带括号传递的原因是数组的名称默认为其第一个条目的地址:


  test(a, &b, result, serie);  
// is the same as  
  test(a,&b, &result[0], &serie[0]);  

要保存原始数组而不修改它,您必须传递数组的副本而不是其地址。我能想到的最简单的方法是将数组包装在一个结构中并按值传递该结构。它会将整个数组复制到本地函数中,并允许您在不影响原始数组的情况下随意使用它。没有办法在 C 中按值传递数组(据我所知)。Deferencing 只返回数组的第一个条目 - C 语言的另一个怪癖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2012-10-19
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多