Difference between pointer and array -- Sun interview

Source: Internet
Author: User

If you can understand this interview question, you can basically understand the difference between the pointer and the array name.
In addition, it's okay to repost an explanation. I am too lazy to write it myself. If you want to know the details, read "C expert programming".
======================
/* File1.c */
Char buff [128];
 
/* File2.c */
Extern char * Buff;/* notice: extern char buff [] */
 
Int main ()
{
* Buff = 'a ';
Return 0;
}
 
The result is as follows:
$ GCC file1.c-C
$ GCC file2.c-C
$ GCC file1.o file2.o-o ff
$./FF
Segmentation fault
 
Q: Why is this result?
 
I tried it. Replace it with extern char buff [] In file2,
But I don't know why ..
 
 
An explanation on the Forum:
---------------------
Arrays and pointers are completely different.
The value of the array element is placed in the array, and the pointer is an address.
The compiler often treats arrays as pointers for processing convenience.
For example:
Int Buf [5] = {0 };
Int * P = Buf;
At this time, the compiler knows that Buf is an array.
Therefore, the array address instead of its content will be passed to the P pointer.
However, if the array is in another compilation unit (the compiler processes each compilation unit independently)
Pointer P. It does not know that it points to an array.
No Buf is an array information during the link.
So at the end of the link, P links the Buf content rather than its address.
 
My experiment results in Linux
---------------------------------
In file1.c
Char Buf [128] = {0x10, 0x20, 0x30, 0x40 };
 
In file2.c
Extern int Buf // note that the char Buf in file1.c is forcibly converted to an integer.
Int main ()
{
Printf ("Buf = % x/N", Buf );
}
The output result is
Buf = 40302010

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.