Array length problem

北慕城南 提交于 2019-12-01 22:34:47

Because int array[] is just a pointer and it's size is same as of int. I think you expected that size of arr will somehow be passed to function, but it doesn't work that way. Size of arr can be determined only in same scope where it was declared, because sizeof actually works at compile time.

The array is passed as a pointer. There is no way for the function to know how much space was allocated to the array.

All arrays decay to pointers when they are passed around, so the expression becomes: sizeof(void*)/sizeof(int) which equates to 1 on 32bit machines with 32bit ints and 2 on 64bit machines with 32bit ints.

You need to pass the length to the function, or create a struct that includes both a pointer to the array and the length of the array. There is no size information stored with C arrays.

An array in C is a very fragile type. There are many situations in which an array decays to a pointer to the first element, and passing an array as an argument of a function is such a situation. Behold:

int main()
{
  char data[10];        // sizeof(data) == 10
  return call_me(data); // data is equivalent to &data[0] here!
}

int call_me(char x[])
// int call_me(char * x)   // same thing!
{
  // here sizeof(x) == sizeof(char *)
  // ...
}

Arrays are peculiar in C in the sense that they cannot be passed as function arguments or returned from functions, so you will frequently see pointers when you expect arrays. It is the responsibility of the caller (you!) to provide enough information to interpret a pointer as an array correctly.

Note that a common C idiom creates an "array" dynamically entirely without ever mentioning an array type: char * p = malloc(10); Here p is never anything but a pointer, and it is entirely up to you to remember that you can treat it as an array.

(The situation is a little better in C++, where you can pass actual arrays by reference.)

See the syntax for the function defination can be written following way

 int DIMension(int array[]) {
 return sizeof(array )/ sizeof(int);
 }


 int DIMension(int *array) 
 {
 return sizeof(array )/ sizeof(int);
 }

int DIMension(int array[10])
{
return sizeof(array )/ sizeof(int);
}

All these three statement has same meaning and common thing across the three is the argument array which is nothing but a pointer to array which is always gonna to be 4 bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!