Search code examples
cdeclarationfunction-callvariable-length-array

this is the question "write a program in C to pass the reference of an array to a function & print that array" ,this is not giving the output ,why?


I got this question asked by one of my peer, as i don't know "C" that much, but still being a beginner i tried solving it, this is the approach i used, but it is not giving the expected output.

According to the question, it should print the entered elements of an array, when we are passing the reference of an array to a function, can anyone review this code ?

#include <stdio.h>
void print(int arr[], int n);

int main(){
    
    int n,i;
    int arr[n];

    printf("enter the size of array :");
    scanf("%d",&n);
    
    
    printf("enter elements :\n");
    for(i=0; i<n; i++){
        scanf("%d",&arr[i]);
    }
    print(&arr[i], n);
    
}

void print(int arr[], int n){
    int i;
    for(i=0; i<n; i++){
        printf("\nentered elements are : %d",arr[i]);
    }
}

Solution

  • This declaration of the variable length array

    int n,i;
    int arr[n];
    

    invokes undefined behavior because the variable n was not initialized.

    Instead you need to write

    int n,i;
    
    printf("enter the size of array :");
    
    if ( scanf("%d",&n) == 1 && n > 0 )
    {
        int arr[n];
        // and so on
    

    This call

    print(&arr[i], n);
    

    again leads to undefined behavior because the value of the variable i is equal to the size of the array. So the expression &arr[i] points to outside the array.

    You need to write

    print( arr, n);
    

    It will be more correctly to declare and define the function like

    void print( const int arr[], int n )
    {
        printf( "\nentered elements are: " );
     
        for ( int i = 0; i < n; i++ )
        {
            printf( "%d ", arr[i] );
        }
        putchar( '\n' );
    }