I want to pass an array to a function in C and iterate through it. I Have this code:
#include <stdio.h>
int funct(int * a);
int main(int argc, char ** argv){
int a[5] = {0};
int b[5] = {1, 1};
printf("Size of cache: %d\n", sizeof(a));
printf("Array values:\n");
printf("Numb of elments in a[]: %d\n", (sizeof(a) / sizeof(a[0])));
for(int i = 0; i < (sizeof(a) / sizeof(a[0])); i++){
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");
printf("Size of cache: %d\n", sizeof(b));
printf("Array values:\n");
printf("Numb of elments in a[]: %d\n", (sizeof(b) / sizeof(b[0])));
for(int i = 0; i < (sizeof(b) / sizeof(b[0])); i++){
printf("for loop\n");
printf("%d\n", b[i]);
}
printf("\n");
funct(a);
funct(b);
return 0;
}
int funct(int * a){
printf("Size of cache: %d\n", sizeof(a));
printf("Numb of elements in a[]: %d\n", (sizeof(a) / sizeof(a[0])));
printf("Array values:\n");
for(int i = 0; i < (sizeof(a) / sizeof(a[0])); i++){
printf("sizeof(a): %d\n",sizeof(a));
printf("sizeof(a[0]): %d\n",sizeof(a[0]));
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");
return 0;
}
The result is:
Size of cache: 20 Array values: Numb of elments in a[]: 5 for loop 0 for loop 0 for loop 0 for loop 0 for loop 0 Size of cache: 20 Array values: Numb of elments in a[]: 5 for loop 1 for loop 1 for loop 0 for loop 0 for loop 0 Size of cache: 4 Numb of elements in a[]: 1 Array values: sizeof(a): 4 sizeof(a[0]): 4 for loop 0 Size of cache: 4 Numb of elements in a[]: 1 Array values: sizeof(a): 4 sizeof(a[0]): 4 for loop 1
Please explain why I can't iterate over the array inside the function - what am I doing wrong (i) and how to to it correctly (ii). Thanks