0

I have the following code:

File1.c

int arr[10];

File2.c

extern int *arr;
int main()
{
    arr[0] = 1;
    return 0;
}

Please explain me why accessing the arr in File2.c will cause segmentation fault?
compiler:gcc OS:Linux.

Pradeep
  • 1,057
  • 2
  • 9
  • 17
  • 1
    Maybe there is a reason the first one is called "array", while the second is called "pointer"? – too honest for this site Feb 23 '16 at 15:20
  • You've not told the compiler the truth,,you've told it there's a variable named `arr` that's an int pointer, but it's actually an array of ints, which is quite different from a pointer to an int. – nos Feb 23 '16 at 15:23
  • @Olaf: yes 'pointer' arr pointing to first element in the array. – Pradeep Feb 23 '16 at 15:23
  • 1
    @Pradeep_Evol: No, it does not! You invoke UB. An array is not a pointer and a pointer is not an array. Please read the standard. And use a header you include in both files! The compiler is your friend. Let it help you detect type errors. – too honest for this site Feb 23 '16 at 15:26
  • @Olaf: What header will help the compiler detect this type error? But in case of character array, array is a pointer . am I correct? – Pradeep Feb 23 '16 at 15:32
  • @Pradeep_Evol: Just as you apparently missed the point: No, it is not a pointer! Because it is an **array**. It is called "array" because it is **not** a pointer! If it **was** a pointer, it would be called "pointer"! Hope that was now clear enough (otherwise I cannot help you further). Please read a C book. You will also see what a header actually is for and how it will help you. – too honest for this site Feb 23 '16 at 15:41
  • `extern int *arr;` is a **pointer** that **points to an integer**. `int arr[10];` is an array **of** integers. A pointer contains an address - which may or may not be valid. An array contains values of whatever base type makes up the array. – Andrew Henle Feb 23 '16 at 15:45
  • @Pradeep_Evol *But in case of character array, array is a pointer . am I correct?* No. A bare array in a statement is **treated as an address that can be assigned to a pointer**. Thus `int array[10]; int *pointer = array;` is valid, but that's only because the bare `array` in the second statement is **treated** as the address of the first element of the array. It's not a pointer - it's the same as `&(array[0])`. – Andrew Henle Feb 23 '16 at 15:50

1 Answers1

2

Reason of error:

This code lead to segmentation fault

int * some_pointer;
...
some_pointer[0] = 1;

You are misunderstood:

The extern int *arr; is declaration of a pointer.

The int arr[10]; is a declaration of an array.

They do not have any relative in your case.

You just need extern int arr[10]; in File2.c

Van Tr
  • 5,889
  • 2
  • 20
  • 44