zoukankan      html  css  js  c++  java
  • 002 C/C++ 数组的传递

    传递一个数组给一个函数的正确做法:

    1.传递数组的内存首地址.

    2.传递数组的有效长度.指数组的元素数量.


     编译器总是将数组类型的变量作为指针传递.

    计算数组的长度: int length = sizeof( a ) / sizeof( a[0] ); 

    如果通过显示取地址的方式传递数组的一部分元素时,请确保length的正确.


    C Sample code:

     1 #include "stdio.h"
     2 #include "stdlib.h"
     3 
     4 //接受一个数组参数的函数:
     5 void SampleArrayParam1( int * a, int length )
     6 {
     7     for( int i = 0; i < length; i++ ) {
     8         printf( "%d ", a[i] );
     9     }
    10     printf( "
    " );
    11 }
    12 
    13 void SampleArrayParam2( int a[], int length )
    14 {
    15     for( int i = 0; i < length; i++ ) {
    16         printf( "%d ", a[i] );
    17     }
    18     printf( "
    " );
    19 }
    20 
    21 void SampleArrayParam3( int a[7], int length ) //a[7]中的'7'在这里无意义的.因为编译器总是传递来一个指针
    22 {
    23     for( int i = 0; i < length; i++ ) {
    24         printf( "%d ", a[i] );
    25     }
    26     printf( "
    " );
    27 }
    28 
    29 void main()
    30 {
    31     int a[] ={ 1,5,8,9,10 };
    32     int length = sizeof( a ) / sizeof( a[0] ); //计算数组的长度.
    33 
    34     //编译器总是将数组类型的变量作为指针传递.所以SampleArrayParam1,SampleArrayParam2,SampleArrayParam3对编译器来说是没有区别的.
    35     SampleArrayParam1( a, length );
    36     SampleArrayParam2( a, length );
    37     SampleArrayParam3( a, length );
    38 
    39     // 通过显式取指针方式,可以传递数组中指定范围内的元素
    40     SampleArrayParam1( &a[1], length - 1 );  //传递数组a的第2元素开始到最后一个元素.
    41     SampleArrayParam2( &a[2], length - 2 );  //传递数组a的第3元素开始到最后一个元素.
    42     SampleArrayParam3( &a[3], length - 3 );  //传递数组a的第4元素开始到最后一个元素.
    43     SampleArrayParam1( &a[4], length - 3 );  //注意:请确保length正确,否则将引起错误.此处length参数(length-3)已经超出了数组a的长度.
    44     system( "pause" );
    45 }

    Output result:

    1 5 8 9 10
    1 5 8 9 10
    1 5 8 9 10
    5 8 9 10
    8 9 10
    9 10
    10 -858993460
    请按任意键继续. . .
    致读者:本人自学编程,知识薄弱,实践经验不够,博客文章难免有错误之处,希望读者能积极指正,感激不尽。 若您有更精妙的解决方案或者对文中有疑问,欢迎留言或联系我讨论问题。
  • 相关阅读:
    LeetCode 1245. Tree Diameter
    LeetCode 1152. Analyze User Website Visit Pattern
    LeetCode 1223. Dice Roll Simulation
    LeetCode 912. Sort an Array
    LeetCode 993. Cousins in Binary Tree
    LeetCode 1047. Remove All Adjacent Duplicates In String
    LeetCode 390. Elimination Game
    LeetCode 1209. Remove All Adjacent Duplicates in String II
    LeetCode 797. All Paths From Source to Target
    LeetCode 1029. Two City Scheduling
  • 原文地址:https://www.cnblogs.com/it89/p/11068654.html
Copyright © 2011-2022 走看看