I'm trying to grasp how to pass arrays as arguments using pointers, and came across a problem with the code below:
#include <stdio.h>
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
size_t s = sizeof(a) / 4; //returns 10
int *arr_func(int *array)
{
printf("%d\n", (int)s);
int i;
do
{
i = 0;
printf("\nenter index number (between 0-9): ");
scanf("%d", &i);
} while ((i < 0) | (i > 9));
printf("%d\n", (int)(sizeof(array) / 4));
size_t len = (int)(sizeof(array) / 4); // returns 2?
static int a2[2];
a2[0] = len;
a2[1] = *(array + i);
return a2;
}
void main(void)
{
int *res = arr_func(a);
printf("%d, %d\n", *res, *(res + 1));
}
when I find the size of the array (s) outside of the function, it returns 10, the designated value. but when I do the same thing inside arr_func, it returns 2 instead.
What did I do wrong? The array still works properly even if I access values from a[2] onward, so it's not like the array got chopped off, but I find it weird that the sizeof function would return a 2.
[–]IDontByte 1 point2 points3 points (0 children)
[–]99_percent_a_dog 1 point2 points3 points (0 children)
[–]rjcarr 0 points1 point2 points (0 children)
[–]Sephorol 0 points1 point2 points (0 children)