-1

See the comment section in the code. There I explained what I want to understand and what I know. enter image description here

How I can get 28 using ptr. sizeof(arr) is giving me 28. (length of array elements) * sizeof(int) But I can't figure out how to get this value using ptr. I want this thing so I can get an array length using this method. In function own here.

int main (void)
{
    int arr[7] = {5, 8, 10, 50, 55, 98, 354};
    int result;

    /* ------- From here ---------*/

    int size = sizeof(arr) / sizeof(int);   // sizeof(arr) = 28, sizeof(int) = 4. So size = 28/4 = 7

    result = anyFunction (arr);

    return 0;
}



int anyFunction (int array[]) 
{   
    int arraySize = sizeof(array) / sizeof(int);   // this line
}


int *ptr = arr; // Same as *ptr = &arr[0]

size = sizeof(ptr); // 8 is the size of pointer.

size = sizeof(*ptr); // size = 4. 4 is the size of arr[0]. Because its pointing to arr[0]. So its sizeof(arr[0]) or sizeof(5)

the busybee
  • 10,755
  • 3
  • 13
  • 30
  • 2
    The compiler doesn't know exactly what a pointer might be pointing to at run-time. It might be pointing to the first element of an array. Or any arbitrary element inside the array. Or to just a single value. And if it points to the first element of an array, which array might it be? A program could use the same function to handle hundreds of different arrays, both created at compile-time, variable-length arrays created at run-time, or dynamically allocated "arrays" from `malloc`. – Some programmer dude Jun 01 '20 at 08:35
  • 1
    Don't post screenshots of error messages. Copy and paste the error message into your question body instead. – Haem Jun 01 '20 at 09:57

1 Answers1

0

If you use sizeof(array) when array is defined as int array[] I expect it to be the same as if it was defined as int *array since the size of the array isn't know.

The obvious solution is add a second parameter to anyFunction() with the array size.

Brecht Sanders
  • 6,215
  • 1
  • 16
  • 40
  • In this case, `array` actually has type `int*` and not `int[]`. C changes a function parameter with array type to have pointer type instead. If you have an actual `int[]` type like `extern int A[];`, then `sizeof(A)` is an error, not the same as `sizeof(int*)`. – aschepler Jun 01 '20 at 12:08