Pointer-array-extern question

后端 未结 5 614
遥遥无期
遥遥无期 2020-12-13 10:02

File 1.c

int a[10];

File main.c:

extern int *a;

int main()
{
    printf(\"%d\\n\", a[0])         


        
5条回答
  •  囚心锁ツ
    2020-12-13 10:48

    Check out the output of the following code.

    File1.c

    #include 
    
    extern int* my_arr;
    
    void my_print()
    {
      printf("%d", my_arr);
    }
    

    main.c

    #include 
    
    int my_arr[2] = {1,2};
    
    extern void my_print();
    
    void main()
    {
        my_print();
    }
    

    output

    1
    

    inside File1.c my_arr is a pointer variable that has the value of 1. meaning the 1st element of my_arr[] was assigned to it. Then if you use *my_arr to access memory location ox1, you get seg fault because you are not allowed to access ox01.

    Why my_arr pointer was assigned 1 (the first element of my_arr[])?

    Has to do with how assembler works. Read this article

    Why your code can't access 0x01 ?

    I know it has to do with the operating system not allowing some address space to be accessed by user code. Thats all I know. google it if you want more info.

提交回复
热议问题