在C中按引用传递数组

时间:2016-10-02 21:07:25

标签: c arrays pass-by-reference

我试图通过引用传递我的数组,以便我可以解决这个事实,即我无法从函数返回一个数组。我相信我正在遵循我所看到的正确的例子。但是出了什么问题?我期待输出为数字0 - 9,但我得到一些奇怪的东西。

目前我的程序没有按照说法执行。它没有做任何计算,它目前仅通过引用测试通过。我想确保在开始尝试任何计算之前我知道如何操作数组。

我要做的是:创建一个数字0-9的数组,通过引用将它传递给一个函数,打印函数中的每个元素。

实际程序将创建一个空数组,将其发送给函数,然后该函数将使用素数填充数组。

#include <stdio.h>

void primesUpTo(int max,int *resPt);
void main()
{
    const int MAX = 10;
    int primes[MAX];

    /*TEST*/for(int i = 0; i < MAX;primes[i] = ++i)

    primesUpTo(MAX,&primes);    
}

/* Primes up to function
 * Fills array that *resPt points to with primes from 0 to 'max'
 *  *resPt: pointer to first element of result array
 *  max: int, highest prime number in result array
 *  
 *  *resPt must be passed as reference
 */
void primesUpTo(int max, int *resPt)
{
    /*TEST*/for(int i = 0; i < max; i++)
        printf("\nTEST: %d",*(resPt + i)); 
}

我的编译错误,然后输出:

steve@steve-VirtualBox:~/C_Programs/CIS/hw_2/ex_3$ gcc -o test printPrimes.c
printPrimes.c: In function ‘main’:
printPrimes.c:11:17: warning: passing argument 2 of ‘primesUpTo’ from incompatible pointer type [-Wincompatible-pointer-types]
  primesUpTo(MAX,&primes); 
                 ^
printPrimes.c:3:6: note: expected ‘int *’ but argument is of type ‘int (*)[(sizetype)MAX]’
 void primesUpTo(int max,int *resPt);
      ^
steve@steve-VirtualBox:~/C_Programs/CIS/hw_2/ex_3$ ./test

TEST: 1835627636
TEST: 1600061541
TEST: 1869833334
TEST: 1952802655
TEST: 0
TEST: 0
TEST: 0
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 1869833334
TEST: 1952802655
TEST: 0
TEST: 0
TEST: 0
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 1952802655
TEST: 0
TEST: 0
TEST: 0
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 0
TEST: 0
TEST: 0
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 0
TEST: 0
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 5
TEST: 0
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 5
TEST: 6
TEST: 0
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 5
TEST: 6
TEST: 7
TEST: 1
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 5
TEST: 6
TEST: 7
TEST: 8
TEST: 0
TEST: 1835627636
TEST: 1
TEST: 2
TEST: 3
TEST: 4
TEST: 5
TEST: 6
TEST: 7
TEST: 8
TEST: 9

1 个答案:

答案 0 :(得分:5)

数组总是通过C中的引用传递。数组的名称是指向它的第一个元素的指针。所以,你这样做: -

void function (int arr[]){
// Some Code.....
}
int main(){
// Some Code...
int name[5];
function(name);
// Some Code...
}

这样可行,您可以修改数组中元素的值,并且更改将反映在调用函数中。

编辑:您知道在for循环后必须添加分号吗?否则,下一行也将被迭代。见 -

Corrected Code  和 Output