Transfer 001 C / C ++ array

Passing an array to a function in the right way:

1. First pass the memory address of the array.

2. The effective length of the array is passed. Number of elements of the group index.


 

The compiler always array type variable passed as a pointer.

Calculating the length of the array: int length = sizeof (a) / sizeof (a [0]); 


C Sample code:

// accepts an array parameter function declaration: 
void SampleArray1 ( int * A, int length) 
{ 
    for ( int I = 0 ; I <length; I ++ ) { 
        the printf ( " % D " , A [I]); 
    } 
    the printf ( " \ n- " ); 
} 

void SampleArray2 ( int A [], int length) 
{ 
    for ( int I = 0 ; I <length; I ++ ) { 
        the printf ( " % D ", a[i] );
    }
    printf( "\n" );
}

void SampleArray3( int a[7], int length )
{
    for( int i = 0; i < length; i++ ) {
        printf( "%d ", a[i] );
    }
    printf( "\n" );
}

void main()
{
    int a[] ={ 1,5,8,9,10};
     Int length = the sizeof (A) / the sizeof (A [ 0 ]); // . Calculating the length of the array 

    // compiler always array type variable passed as pointers 
    SampleArray1 (A, length); 
    SampleArray2 (A , length); 
    SampleArray3 (a, length); 
    SampleArray1 ( & a [ . 1 ], length - . 1 );   // array is passed to the last element of the second element to function. 
}

 

Guess you like

Origin www.cnblogs.com/it89/p/11068654.html