C语言 - 数组作为参数传递给函数(按值传递和按引用传递)

测试数组作为参数传递给函数,在函数中访问和修改。并且,这表明C语言的数组作为参数传递给函数时,是作为引用方式传递的。
    还有,在传递的时候,还需要把数组的大小也一并传递给函数。因为只传递数组给函数,进而想要在函数中获得数组大小,在网上搜了一下,答案居然是“No way”……

    另外,如果函数的原型是void function(int array[],int c),但是function(array[],i);的写法却引发了syntax error,看来这么着是不行的。改为function(array,i);却没有问题。这也从另一个角度验证了按引用传递的解法
    代码在此:
——————————————————————————————————
 /*
an unknown-length-array as a parameter of the function
*/

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

//the function accepted an array as a parameter,show the array.
void ShowArray(int array[],int c)
 {
  puts(“\nNow output the array:\n”);
  int i;
  for(i=0;i<c;i++)
   {
    printf(“%3d is %5d.\n”,i,array[i]);
   }
 }//end ShowArray

//the function accepted an array as a parameter,modify the array.
void ModifyArray(int array[],int c)
 {
  puts(“\nNow you can modify the array:\n”);
  int i;
  for(i=0;i<c;i++)
   {
    printf(“input the %d element of the array:\n”,i);
    scanf(“%d”,&(array[i]));
   }
 }//end ModifyArray

//main program here
main()
{
 puts(“\nInput your array count:\n”);
 int i;
 scanf(“%d”,&i);
 int array[i];
 
 //ShowArray(array[],i);//syntax error before ‘]’ token
 ShowArray(array,i);
 
 ModifyArray(array,i);
 
 ShowArray(array,i);
}//end main

/*
output:

D:\C_test>unknownArrayParameter.exe

Input your array count:

5

Now output the array:

  0 is 2293536.
  1 is 4199472.
  2 is 2293728.
  3 is 2009095316.
  4 is 2008958752.

Now you can modify the array:

input the 0 element of the array:
1
input the 1 element of the array:
2
input the 2 element of the array:
3
input the 3 element of the array:
4
input the 4 element of the array:
5

Now output the array:

  0 is     1.
  1 is     2.
  2 is     3.
  3 is     4.
  4 is     5.

D:\C_test>
*/

—————————————————————————————————–

    但是,简单类型,如int,在传递给函数的时候是按值传递的,即,传递给函数的是这个变量的值(变量的副本),并不是变量本身(变量的存储地址)。相对的,函数内对于变量的改变也只限于函数内部。也就是说,变量没有真正的被改变。一下程序做了验证。
    代码:
—————————————————————————————————

/*
to look up passing a parameter by value
*/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

//the exchange function
void ExchangeBy(int x,int y)
 {
  int temp;
  temp=x;
  x=y;
  y=temp;
 }//end ExchangeBy

//main program here
main()
{
 puts(“\nenter you two numbers:\n”);
 int x;
 puts(“input x:\n”);
 scanf(“%d”,&x);
 int y;
 puts(“input y:\n”);
 scanf(“%d”,&y);
 
 ExchangeBy(x,y);
 
 puts(“After exchange function:\n”);
 printf(“x is %d,y is %d.”,x,y);
}//end main

/*
Output here:

D:\C_test>passingParameterByvalue.exe

enter you two numbers:

input x:

1
input y:

2
After exchange function:

x is 1,y is 2.
D:\C_test>
*/

转载于:https://my.oschina.net/alphajay/blog/68698

    原文作者:chenqiechun3408
    原文地址: https://blog.csdn.net/chenqiechun3408/article/details/100999589
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞