Search code examples
arrayscfunctiondeclarationvariable-length-array

Array using functions on C


A program to accept an array and diplay it on the console using functions. Program should contain 3 functions including main() function. Next two functions for accepting values to the array, and display array values on the console respectively.

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

void getarray(int a[],int size);
void displayarray(int a[],int size);

int main(void) {
    int a[20],size;
    getarray(a,size);
    displayarray(a,size);
    return EXIT_SUCCESS;
}

void getarray(int a[],int size){
    int i;

    printf("enter the size of the array");
    scanf("%d",&size);

    for(i=0;i<size;i++){
        scanf("%d",&a[i]);
    }
}

void displayarray(int a[],int size){
    int i;

    for(i=0;i<size;i++){
        printf("%d\t",a[i]);
    }
}

This is what I tried. I did'nt get proper output.

My output:

Enter the size of the array3
1
2
3

And stopped here.

What are the mistake in it? Or is there another way to get result?


Solution

  • As stated in comments, the problem is that size in main and size in getarray are different variables, i.e. changing size inside the function doesn't change it in main.

    The answer from @TedLyngmo shows a way to solve the problem using pointers.

    Another solution is to let getarray return the size. And perhaps use an unsigned type for size.

    unsigned getarray(int a[]) {
        unsigned i, size;
    
        printf("enter the size of the array");
    
        if (scanf("%u", &size) != 1) return 0;
    
        for (i = 0; i < size; i++) {
            scanf("%d", &a[i]);
        }
        return size;
    }
    

    and call it like

    size = getarray(a);
    

    BTW: For a real program you should also add code to handle cases where a user inputs a size that are too big for the array.