What is wrong with this C program using the extern keyword?

I want to use the variable a from foo.c in main.c, and I write:

foo.c
#include <stdio.h>

int a[] = {3, 2};

void foo()
{
    printf("foo\taddress of a:%x\n", a);
    printf("foo\tvalue of a[0]:%x\n", a[0]);
}

main.c
#include <stdio.h>

extern int *a;

int main(void)
{
    foo();
    printf("main\taddress of a : %x\n", a);
    printf("main\tvalue of a[0] : %x\n", a[0]);

    return 0;
}

and the result:

foo address of a:804a014
foo value of a[0]:3
main    address of a : 3
Segmentation fault (core dumped)

why?

+5
source share
2 answers

Type a- int[2]and not int*. Please try again with

extern int a[2];

The C compiler cannot check the type of source code files . Therefore, when you say int* a, the compiler will assume that you are telling the truth, use pointer semantics and not throw any compiler error.

There are slight differences between arrays and pointers. Let it be assumed a 32-bit system. Then the contents of "a" will be distributed as follows:

    a
0x100 0x104 0x108 ← address
    +-----------+----------+
    |         3 |        2 |   ← content
    +-----------+----------+

a ,

  • a a. a , "0x100".
  • a[n] C *(a + n), .. a n , . , a[0] *0x100, 0x100, .. "3" .

a ,

  • "" a - . , - . a , .. "3" .
  • a[n] - *(a + n). , a[0] *3, , "3" .
+8

, .

int a[] = {2, 3};, extern int a[]; extern int a[2]; , extern int *a; , .

, , - , "" ( &) sizeof, . , , .

. , a ( ) printf , printf, &.

#include <stdio.h>

void print_array_info(void)
{
    extern int a[];
    printf("address of a:  %p\n", (void*) &a);   // prints address of a
    printf(" converted a:  %p\n", (void*) a);    // prints address of a[0]
    printf("value of a[0]: %x\n", a[0]);         // prints value of a
}

void print_pointer_info(void) {
    extern int a[];
    int *b = a; // == &a[0]

    printf("address of b:  %p\n", (void*) &b);  // prints address of b
    printf("  value of b:  %p\n", (void*) b);   // prints value of b (== &a[0])
    printf("value of b[0]: %x\n", b[0]);        // prints value of b[0] (== a[0])
}

, %p void*.

+1

All Articles