Why do C and C++ compilers allow array lengths in function signatures when they're never enforced?

后端 未结 10 1628
终归单人心
终归单人心 2020-11-22 06:59

This is what I found during my learning period:

#include
using namespace std;
int dis(char a[1])
{
    int length = strlen(a);
    char c = a         


        
10条回答
  •  忘掉有多难
    2020-11-22 07:49

    The length of the first dimension is ignored, but the length of additional dimensions are necessary to allow the compiler to compute offsets correctly. In the following example, the foo function is passed a pointer to a two-dimensional array.

    #include 
    
    void foo(int args[10][20])
    {
        printf("%zd\n", sizeof(args[0]));
    }
    
    int main(int argc, char **argv)
    {
        int a[2][20];
        foo(a);
        return 0;
    }
    

    The size of the first dimension [10] is ignored; the compiler will not prevent you from indexing off the end (notice that the formal wants 10 elements, but the actual provides only 2). However, the size of the second dimension [20] is used to determine the stride of each row, and here, the formal must match the actual. Again, the compiler will not prevent you from indexing off the end of the second dimension either.

    The byte offset from the base of the array to an element args[row][col] is determined by:

    sizeof(int)*(col + 20*row)
    

    Note that if col >= 20, then you will actually index into a subsequent row (or off the end of the entire array).

    sizeof(args[0]), returns 80 on my machine where sizeof(int) == 4. However, if I attempt to take sizeof(args), I get the following compiler warning:

    foo.c:5:27: warning: sizeof on array function parameter will return size of 'int (*)[20]' instead of 'int [10][20]' [-Wsizeof-array-argument]
        printf("%zd\n", sizeof(args));
                              ^
    foo.c:3:14: note: declared here
    void foo(int args[10][20])
                 ^
    1 warning generated.
    

    Here, the compiler is warning that it is only going to give the size of the pointer into which the array has decayed instead of the size of the array itself.

提交回复
热议问题