Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the pointer hack for finding the size of an array in C giving different value when used in a called function [duplicate]

Tags:

arrays

c

function

This is the code below to illustrate the issue:

#include <stdio.h>

void func(int arr[]);

int main() {
    int arr[10];
    int n = *(&arr + 1) - arr;
    printf("%d\n", n);
    func(arr);
    return 0;
}

void func(int arr[]) {
    int n = *(&arr + 1) - arr;
    printf("%d\n", n);
}

Output of the above code is:

10
268435906
like image 758
Abhishek Ghosh Avatar asked Dec 06 '22 11:12

Abhishek Ghosh


1 Answers

Despite the syntax used for its definition void func(int arr[]), function func receives a pointer to the first element of the array. The definition is clearer as void func(int *arr).

The expression *(&arr+1)-arr evaluates at compile time to the number of elements of an array only if arr is defined as an array. If arr is a pointer, it dereferences memory after the pointer and subtracts the pointer value, which is meaningless and in most circumstances has undefined behavior.

A more common (and more readable) expression to get the number of element of an array is

n = sizeof(arr) / sizeof(*arr);

If arr is an array, dividing its size in bytes by the size of an element in bytes produces the number of elements. The expression is evaluated at compile time, no runtime overhead. If arr is a pointer, dividing its size by the size of the type it points to is defined, but useless, just like your expression.

like image 57
chqrlie Avatar answered May 17 '23 11:05

chqrlie