Search code examples
carraysfunctionfunction-calls

displayArray Function For c


I am new in c programming and I am studying arrays right now. I saw that unlike java you can't print them automatically by using Arrays.toString() method. I want to write a simple function that prints the array.

In the program it asks us the size of the array and when we write it, it asks what is the value for each element and then the program calls the displayArray() function to print the array on a single line.

For example :

Hello. What will be the size of the new array?

3

Enter the 1. element

7

Enter the 2. element

5

Enter the 3. element

1

The result should be "Your array is: 7 5 1" but instead of that I get "Your array is: 3 6356728 2" as a result. Can you help?

#include <stdio.h>

void displayArray();

int main()
{
    int size;
    printf("Hello. What will be the size of the new array?\n");
    scanf("%d", &size);

    int myarray[size];

    for (int i = 0; i < size; i++)
    {
        printf("Enter the %d. element\n" , (i + 1));
        scanf("%d", &myarray[i]);
    }

    displayArray(myarray[size], size);

    return 0;
}

void displayArray(int myarray[], int size)
{
    printf("Your array is: ");
    for (int i = 0; i < size; i++)
    {
         printf("%d ", myarray[i]);
    }
    return;
}

Solution

  • You have a problem in the function call (which your compiler should have warned you about, read the footnote later)

       displayArray(myarray[size], size);
    

    should be

       displayArray(myarray, size);
    

    because,

    1. Type mismatch between formal parameter and actual argument: you function expects an array (a pointer to the first element of the array, to be precise), not an element of the array.
    2. undefined behavior. For an array defined as int myarray[size], accessing element like myarray[size] is off-by-one, as C arrays are 0-based indexing.

    Footnote:

    If you try to compile your code, compiler should complain about the mismatch. It can happen either

    • You did not turn up the compiler warning level (which is a mistake from your side)

    • or, you chose to ignore the warnings (which is an "offense" from your side)