Introduction to arrays and pointers

Source: Internet
Author: User
Tags array definition
Document directory
  • This should not discuss data and pointers. It should be reading notes! However, this question is better.
  • Chapter 4 of Expert C Programming: shocking fact: arrays and pointers are different. I also learned a lot about myself. I learned a lot about the basic things, which is very helpful to those who are new to C developers. Let's talk about it.
  • We always think that data and pointers are completely the same, and the two are interchangeable. This is one-sided. We often use global variables in programming. This global variable can also be declared in other files. The following is an example:
  • /* Some code using mango */
  • Here, file 1 defines the int variable mango, but file 2 declares it as the pointer int * type. Here it is obviously a Type mismatch, which also indicates that the array and pointer are not exactly the same. This operation is definitely incorrect, and the code cannot run normally. How should we declare it as follows:
  • 1. What is declaration? What is definition?
  • In C language, objects must have only one definition, but can have multiple declarations. A definition is a special declaration that creates an object. A declaration only indicates that this object is created elsewhere and can be used here:
  • **************************************** ***************************************
  • The definition can only appear in one place to determine the object type and allocate memory, used to create a new object
  • The Declaration can appear multiple times to describe the object type, used to refer to objects defined elsewhere
  • **************************************** ***************************************
  • Just remember the following content to clearly define and declare:
  • A declaration is equivalent to a general statement: It describes objects created elsewhere rather than itself.
  • The definition is equivalent to a special declaration: it allocates memory for the object.
  • The extern object Declaration tells the compiler object type and name, and the object memory is allocated elsewhere. Since the array is not allocated memory in the Declaration, it is not necessary to provide information about the array length. For multi-dimensional arrays, the length of the dimension except the leftmost one must be provided-this gives the compiler enough information to generate the corresponding code.
  • 2. How to access arrays and pointers
  • Here is the difference between array reference and pointer reference. The first thing to note is the difference between "address y" and "address y content. This is quite subtle. In most programming speech, we use the same symbol to represent these two things. The Compiler judges their meanings based on the context. Here is a simple example:
  • The symbol that appears on the left of the value assignment operator is called the left value (because it is located on the "left-hand side" or "indicating the location "), the symbol that appears on the right of the value assignment is sometimes called the right value (because it is on the right hand side ). The compiler assigns an address (left value) to each variable. This address is known during compilation, and the variable remains at this address during runtime. On the contrary, the value (Right Value) stored in the variable is only known at runtime. If you need to use the value stored in the variable, the compiler will send the quality to read the variable from the specified address and store it in the register.
  • This is why in the IF (-1 = x) Judgment statement, if "=" is mistakenly written as "=", the compiler will trigger an alarm. (I believe many people only know why it is used ?)
  • The key here is that each symbol is known during compilation. So if the compiler needs an address (which may also need to be offset) to execute some operation. It can perform operations directly without adding a command to obtain the specific address first. On the contrary, it can obtain the current value of the pointer at runtime before it can be referenced. For details, see:
  • This is why extern char a [] is equivalent to extern char a [100. Both indicate that A is an array, that is, a memory address. The characters in the array can be found from this address. The compiler does not need to know how long this address is, because it only generates an offset from the starting address. Extract A value from the data. You only need to simply know the actual address of a and add a subscript. The required character is in this address.
  • Conversely, if extern char * P is declared, it tells the compiler that p is a pointer and points to a character. To obtain this character, you must know the content of P and take it as the character address. The pointer access is flexible, but an additional extraction is required.
  • Now let me look at the definition as a pointer. What will happen when referenced in array mode? Let's look at the example below:
  • Another array:
  • In the C standard, the following statement is made:
  • Rule 1: The array name in the expression (different from the declaration) is used by the compiler as a pointer to the first element of the array.
  • Rule 2: The subscript is always the same as the pointer offset.
  • Rule 3: In the function parameter declaration, the array name sad compiler acts as a pointer to the first element of the array.
  • The following describes the meanings of these three rules in detail:
  • Rule 1: "expression array name" is a pointer
  • The rule 1 and 2 above can be understood as "a pointer pointing to the starting address of the array plus an offset" for the reference of the array subject ". For example, if we declare:
  • Rule 2: the C language uses the array subscript as the pointer offset
  • We usually think that using pointers is more efficient than writing arrays. This statement is generally incorrect. The code generated by one-dimensional arrays and pointer references is not significantly different. Here, you can refer to the previous content and study it yourself.
  • Rule 3: array names used as function parameters are equivalent to pointers.
  • How is an array parameter referenced?
  • Demonstrate the steps required to access an array parameter in the subscript form:
  • Note: One operation can only be performed in the pointer but not in the array, that is, to modify its value. The array name is an unchangeable left value, and its value cannot be changed.
This should not discuss data and pointers. It should be reading notes! However, this question is better. Chapter 4 of Expert C Programming: shocking fact: arrays and pointers are different. I also learned a lot about myself. I learned a lot about the basic things, which is very helpful to those who are new to C developers. Let's talk about it. We always think that data and pointers are completely the same, and the two are interchangeable. This is one-sided. We often use global variables in programming. This global variable can also be declared in other files. The following is an example:

File 1:

Int mango [100];

File 2:

Extern int * mango ;/**/

...

/* Some code using mango */here, file 1 defines the int variable mango, but file 2 declares it as the pointer int * type, which is obviously a Type mismatch, it also shows that arrays and pointers are not exactly the same. This operation is definitely incorrect, and the code cannot run normally. How should we declare it as follows:

Extern int mango 【];/**/

Note:
① Statement declaration mango is an int * type; ② declaration mango is an int type array, the length is not yet determined, and its storage is defined elsewhere.

1. What is declaration? What is definition? In C language, objects must have only one definition, but can have multiple declarations. A definition is a special declaration that creates an object. A declaration only indicates that this object is created elsewhere and can be used here: **************************************** ************************************* Definition the object type can only appear in one place and the memory can be allocated, this interface is used to create a new object declaration that can appear the type of the description object multiple times, used to refer to objects defined elsewhere ********************************* **************************************** * ***** you only need to remember the following content to distinguish between definitions and declarations: A declaration is equivalent to a general statement: It describes objects created elsewhere rather than itself. The definition is equivalent to a special declaration: it allocates memory for the object. The extern object Declaration tells the compiler object type and name, and the object memory is allocated elsewhere. Since the array is not allocated memory in the Declaration, it is not necessary to provide information about the array length. For multi-dimensional arrays, the length of the dimension except the leftmost one must be provided-this gives the compiler enough information to generate the corresponding code. 2. How to access arrays and pointers here we will talk about the differences between array references and pointer references, note the difference between "address y" and "address y content. This is quite subtle. In most programming speech, we use the same symbol to represent these two things. The Compiler judges their meanings based on the context. Here is a simple example:

The symbol that appears on the left of the value assignment operator is called the left value (because it is located on the "left-hand side" or "indicating the location "), the symbol that appears on the right of the value assignment is sometimes called the right value (because it is on the right hand side ). The compiler assigns an address (left value) to each variable. This address is known during compilation, and the variable remains at this address during runtime. On the contrary, the value (Right Value) stored in the variable is only known at runtime. If you need to use the value stored in the variable, the compiler will send the quality to read the variable from the specified address and store it in the register. This is why in the IF (-1 = x) Judgment statement, if "=" is mistakenly written as "=", the compiler will trigger an alarm. (I believe many people only know why it is used ?) The key here is that each symbol is known during compilation. So if the compiler needs an address (which may also need to be offset) to execute some operation. It can perform operations directly without adding a command to obtain the specific address first. On the contrary, it can obtain the current value of the pointer at runtime before it can be referenced. For details, see:

This is why extern char a [] is equivalent to extern char a [100. Both indicate that A is an array, that is, a memory address. The characters in the array can be found from this address. The compiler does not need to know how long this address is, because it only generates an offset from the starting address. Extract A value from the data. You only need to simply know the actual address of a and add a subscript. The required character is in this address. Conversely, if extern char * P is declared, it tells the compiler that p is a pointer and points to a character. To obtain this character, you must know the content of P and take it as the character address. The pointer access is flexible, but an additional extraction is required.

Defined as a pointer, but referenced as an array

Now let me look at the definition as a pointer. What will happen when referenced in array mode? Let's look at the example below:

See Figure C's access method.

Char * P = "abcdefgh";... P [3]

And figure A's access method:

Char A [] = "abcdefgh";... A [3]

In both cases, the character 'D' can be obtained, but the two methods are different.

When the extern char * P is written and then the element is referenced by P [3], the essence is the combination of access methods in Figure A and Figure B. First, perform indirect reference as shown in Figure B. Then, a uses the subscript as the offset for direct access. More formally, the compiler will:

1.
Obtain the P address and extract the pointer stored here.

2.
Add the offset indicated by the subscript to the pointer value to generate an address.

3.
Access the above address to obtain the value.

This may already know why extern int * mango;/* is declared in file 2 in the example at the beginning of the article ;/**/

Why does compilation fail? Since P is declared as a pointer, no matter whether P was originally defined as a pointer or an array, it will follow the three steps shown above, but only when P was originally defined as a pointer, the above method is correct. Consider the problem above. When Mango [I] is used to extract the declared content, it is actually a character. According to the above method, the compiler regards it as a pointer, it is obviously wrong to regard accios as addresses.

Differences between arrays and pointers:

No

Pointer

Array

1

Data storage address

Save data

2

Simple access to data. First, get the pointer content, treat it as an address, and then extract data from this address. If the pointer has a subscript [I], use the I address in the pointer to extract data from it.

Access data directly. A [I] simply retrieves an array with a + I as the address.

3

Usually used for dynamic memory allocation

Usually used for a fixed number of elements with the same data type

4

Related functions malloc () and free ()

Stealth allocation and Deletion

5

Usually refers to anonymous data

Itself is the data name

 

Another array:

1,
When is the array and pointer the same?

In practice, the scenario of array and pointer swapping is more common than that of the two. Let's consider the situations of "Declaration" and "use" respectively.

 

The statement can also be divided into three situations:

ØExternal array declaration;

ØArray definition (Remember, definition is a special case of declaration. It allocates memory space and provides an initial value );

ØFunction parameter declaration.

All array names used as function parameters can always be converted to pointers by the compiler. In other cases, the declaration of an array is an array, and the declaration of a pointer is a pointer. The two cannot be confused. However, when using arrays, Arrays can always be written as pointers, and they can be exchanged. The following is a summary:

 

Why is obfuscation?

 

When people learn programming, they always put all the code in a function at first. As the level progresses, they place the code in several functions. After the level continues to improve, they finally learned how to construct a program using several files. In this process, they can see a large number of arrays and pointers as function parameters. In this case, they are completely interchangeable, as shown below:

char my_array[10];char *my_ptr;...i = strlen(my_array);j = strlen(my_ptr);printf("%s,%s",my_array,my_ptr);

The above clearly shows the course swapping of arrays and pointers. It is easy to ignore that this is just stored in a specific context environment, that is, used as a function call parameter. Worse, it can be written as follows:

Printf ("array at LOCATION % x holds string % s", a, );

In the same statement, the array name is used as an address (pointer), and the array name is used as a character array.

 

In the C standard, the following declaration is made for "when the array and pointer are the same": Rule 1: The array name in the expression (different from the Declaration) the compiler acts as a pointer to the first element of the array. Rule 2: The subscript is always the same as the pointer offset. Rule 3: In the function parameter declaration, the array name sad compiler is used as a pointer to the first element of the array. The following describes the meaning of these three rules in detail: Rule 1: the expression array name is understood by the Rule 1 and 2 above, that is, it can always be written as "a pointer pointing to the starting address of the array plus an offset" for the reference of the array underlying object ". For example, if we declare:
Int A [10], * P, I = 2;/* We can use the following centralized method to access a [I] */P = A; P [I]; /****************/P = A; * (p + I ); /*****************/P = a + I; * P;

There should be many other methods. Array references, such as a [I], are always rewritten by the compiler into the form of * (a + I) during compilation. The C language requires the compiler to have this conceptual behavior. The subscript in pointer or array name + square brackets [] is the address of the access element, and then its value. Therefore, you also remember that pointers and arrays can be exchanged in expressions, because they are ultimately in the form of pointers in the compiler. Therefore, we can understand why the following value representation method is the same and correct.

a[6] = ......;6[a] = .....;
Rule 2: the C language uses the array subscript as the pointer offset. We usually think that when writing an array algorithm, using a pointer is more efficient than an array. This statement is generally incorrect. The code generated by one-dimensional arrays and pointer references is not significantly different. Here, you can refer to the previous content and study it yourself. Rule 3: array names used as function parameters are equivalent to pointers.
Terms Definition Example
Parameter) It is a variable in the function definition or declaration prototype.
. Also known as form parameters
Int power (INT base; int N );
Base, N are all form parameters
Real parameter (argument) The value passed to the function during the actual function call. I = power (10, 2 );
10 and 2 are real parameters,

According to the standard, the declaration of the form parameter of the type array should be adjusted to the type pointer. The three methods below are the same

my_function (int *a);my_function (int a[]);my_function (int a[200]);
How is an array parameter referenced? Demonstrate the steps required to access an array parameter in the subscript form:

Note: One operation can only be performed in the pointer but not in the array, that is, to modify its value. The array name is an unchangeable left value, and its value cannot be changed.

 

 

 

 

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.