Usable case of pointer to array with unspecified bounds in C++ (not in C)

前端 未结 2 708
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 11:58

Consider following code:

int main() {
    int (*p)[]; // pointer to array with unspecified bounds

    int a[] = {1};
    int b[] = {1,2};

    p = &a; /         


        
2条回答
  •  离开以前
    2020-12-24 12:25

    I think a compiler should accept it (irrespective of the -O setting) because a definition of the static can be provided by another compilation unit. (This is perhaps a pragmatic deviation from the standard - I'm not an C++ expert.) The posted snippet can be compiled, but it is incomplete and cannot be brought to execution without a definition of the static member.

    File c.h:

    struct C {
        static int v[];
    };
    

    File x.cpp

    #include "c.h"
    #include 
    int main(){
        int (*p)[] = &C::v; // works in C++ if 'v' isn't defined (only declared)
        std::cout << (*p)[0] << std::endl; 
        return 0;
    }
    

    File y.cpp

    #include "c.h"
    int C::v[3] = {1,2,3};
    

    Compiled and linked using (dont-tell-me-it's-old) g++ 4.3.3. Prints 1.

提交回复
热议问题