Dok
Dok

Reputation: 71

Function printArray not working properly

I'm trying to make function that prints array but the output of it is wrong. Can someone help me please?

This is the code:

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    void printArr(int arr[],int size);

    int main()
    {
        int arr1[3] = { 1,2,3 };
        int arr2[5] = { 1,2,3,4,5 };

        printf("arr1: \n");
        printArr(arr1, 3);

        printf("\n\narr2: \n");
        printArr(arr2, 5);
        printf("\n\n");

        return(0);
    }

    void printArr(int arr[], int size)
    {
        int i;
        for (i = 0; i < size; i++);
        {
            printf("%d", arr[i]);
        }

}

What I get is:

enter image description here

Upvotes: 0

Views: 125

Answers (1)

P.P
P.P

Reputation: 121347

Remove the semi-colon at the of for:

for (i = 0; i < size; i++);
                          ^^^

That makes the for loop run size times and executes the block after that. But by that time, i value is equal to size. This leads to out of bound access, which is undefined behaviour. Clearly, this is not what you intention was.

Upvotes: 3

Related Questions