Home > Enterprise >  How to print an array using a function?
How to print an array using a function?

Time:01-29

Could anyone help explain why my code doesn't work? I want to print an array by passing the whole array into a function as its parameters.

#include <stdio.h>

void printArray(int *array);

int main(void)
{
    int array[] = {0, 1, 2, 3, 4, 5, 6};

    printArray(array);

}

void printArray(int *array)
{
    int sizeArr = sizeof(*array) / sizeof(int);

    for (int i = 0; i < sizeArr; i  )
    {
        printf("%i ", array[i]);
    }

    printf("\n");
}

CodePudding user response:

Your parameter has changed from a array to a pointer, so the: sizeof(*array) / sizeof(int); is always return 1. you need to change the function definition to like below:

void printArray(int *array, int len)
{
    for (int i = 0; i < len; i  )
    {
        printf("%i ", array[i]);
    }

    printf("\n");
}

CodePudding user response:

Copy-paste this.

#include <stdio.h>

void printArray(int *array);

int main(void)
{
    int array[] = {0, 1, 2, 3, 4, 5, 6};

    printArray(array);

}

void printArray(int *array, int len)
{
    for (int i = 0; i < len; i  )
    {
        printf("%i ", array[i]);
    }

    printf("\n");
}
}
  •  Tags:  
  • Related