Array length problem

后端 未结 6 1488
栀梦
栀梦 2021-01-21 07:46

I was reading a csc placement paper where I read a question related to c language array\'s sizeof() operator. Answer was something else then i expected it to be.



        
相关标签:
6条回答
  • 2021-01-21 08:22

    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.

    0 讨论(0)
  • 2021-01-21 08:23

    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

    0 讨论(0)
  • 2021-01-21 08:29

    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.

    0 讨论(0)
  • 2021-01-21 08:39

    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.

    0 讨论(0)
  • 2021-01-21 08:41

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

    0 讨论(0)
  • 2021-01-21 08:44

    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.)

    0 讨论(0)
提交回复
热议问题