-3
#include<stdio.h>
void func(int x[]);
main()
{
    int a[]={1,2,3,4};
    printf("size of %d \n",sizeof(a));  // Some value I'm getting
    func(a);
}
void func(int a[]) 
{
    printf("size of %d",sizeof(a));  // Value is changing
}

Both times, the value of 'a' is not printing the same. To get the same value by maintaining this code, what more code need to be added or any changes required?

I don't want to change the signature of any function. Without changing the signature, what extra code is needed to be added inside func(int a[])?.

4

1 回答 1

4

数组函数参数衰减为指针,这意味着参数func的类型为int*。因此,您只能sizeof(int*)在里面计算func

如果要传递数组大小,可以将其作为单独的参数传递

func(a, sizeof(a)/sizeof(a[0]));
....
void func(int* a, int num_elems);

或初始化a以包含一个标记数组结束的标记值并遍历元素,直到在func.

于 2013-04-20T07:24:07.567 回答