diffrent results when trying to find length of an array using pointer arithmetic inside a function and inside of main

huangapple go评论64阅读模式
英文:

diffrent results when trying to find length of an array using pointer arithmetic inside a function and inside of main

问题

有一个奇怪的原因,当我运行这段代码时:

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

我得到一个地址,

当我在主函数内运行相同的代码时,我得到数组的长度。

有什么想法吗?

当我在主函数内运行它时,它给我数组的长度,当我在一个函数内运行它时,它给我一个地址。

英文:

for some odd reason when I run this code:

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

I get an address,

and when I run the same code inside main I get the length of the array.

any idea why?

I ran it inside main and it gave me the length of an array, and when I ran it inside a function it gave me an address.

答案1

得分: 3

这个函数声明

int func(int arr[], int n){

由编译器调整为

int func(int *arr, int n){

另一方面,作为参数表达式传递给函数的数组会被隐式转换为类型为 int * 的第一个元素的指针。

因此,在函数内部,实际上处理的是一个指针而不是一个数组。

在任何情况下,在函数内部使用指针的这一行表达式

int a = *(&arr + 1) - arr;

是无效的并且会引发未定义行为。

英文:

This function declaration

int func(int arr[],int n){

is adjusted by the compiler to

int func(int *arr,int n){

On the other hand. the array passed to the function as an argument expression is implicitly converted to a pointer to its first element of the type int *.

So within the function you actually deal with a pointer instead of an array.

In any case the expression with pointers used in this line within the function

int a = *(&arr + 1) - arr;

is invalid and invokes undefined behavior.

huangapple
  • 本文由 发表于 2023年2月19日 20:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定