'How to print an array using a function?
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");
}
Solution 1:[1]
Your parameter has changed from an array to a pointer, so sizeof(*array) / sizeof(int) is always 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");
}
Solution 2:[2]
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");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dada |
| Solution 2 | ??????? ?????????? - ??????? |
