Introduction to pointer in C Language

Source: Internet
Author: User
Tags define null
Description

Joel Spolsky believes that the understanding of pointers is an aptitude, which can be achieved without training. Even so, I 'd like to talk about the strongest and most error-prone elements in this C/C ++ language.

In view of the association between pointers and the current computer memory structure, many essential features of C language are rooted in them. Therefore, I will take pointers as the main line in this article and articles 6 and 7, based on the problems encountered in actual programming, let's talk in detail about several important aspects of pointers.

Essential Analysis of pointer types

1. essence of pointers

Pointer essence: A composite data type. Below I will take the following examples for analysis:

A), int * P;
B), int ** P;
C), INT (* parvalue) [3];
D), INT (* pfun )();

Analysis:

The so-called data type is something with certain data features, such as the data type char. Its data feature is that it occupies 1 byte of memory, and the pointer is similar, the Pointer Points to a value that occupies an address in the memory. The address length is related to the pointer type. For example, for a char pointer, the pointer occupies 1 byte of memory, therefore, pointers are also a data type, but we know that pointers also occupy a memory space address. The address length is related to the machine's word length. For example, in a 32-bit machine, the length is 4 bytes, so the pointer itself is also a data type. Therefore, we say that the pointer is actually a composite data type,

Now we can analyze the above examples.

Suppose the following is the definition:

Int nvalue;

Then, the nvalue type is int, that is, the remaining part of the nvalue variable is removed. Therefore, the above four statements can be analyzed by analogy:

A), int *

* Indicates that the value of the variable (pointer itself) is an address, and INT indicates that the address contains an integer. The two are combined, and int * defines a pointer to an integer, and so on:

B), int **

A pointer to an integer.

C), INT (*) [3]

Pointer to an array with three integers.

D), INT (*)()

Pointer to a function. The function parameter is null and the return value is an integer.

The analysis ends. From the above we can see that the pointer has two aspects: one is its own value, which is the address in the memory; the other is the object pointed to by the pointer, this address stores data of various meanings.

2. Analysis of pointer values

The following example shows the pointer value (a 32-bit computer in the environment ):

Void * P = malloc (100 );

Calculate sizeof (p) =?

Char STR [] = "hello ";
Char * P = STR;

Calculate sizeof (p) =?

Void func (char STR [1, 100])
{
Calculate sizeof (STR) =? // Note that STR has been degraded to a pointer. For details, see
// Next pointer and array
}

Analysis: In the above example, the answer is 4, because we can see from the above discussion that the pointer value corresponds to an address in the memory, its size is only related to the machine's font length (that is, it is determined by the system's memory model). In 32-bit machines, this length is 4 bytes.

3. Analysis of the things pointed to by the pointer

Now we will analyze the meaning of the object pointed to by the pointer in the second part of the composite type.

We have obtained the pointer type above, so we can remove the "*" of the pointer type to get the type of the object pointed to by the pointer, as follows:

A), int

The object is an integer.

B), int *

The object is a pointer to an integer.

C), INT () [3]

() Is null. you can remove it and change it to int [3]. The pointed object is an array with three integers.

D), INT ()()

The first () is null, which can be removed and changed to int (). The pointing object is a function. The parameter of this function is null and the return value is an integer.

4. Additional Analysis

In addition, the pointer size is different from C in C ++. I will also discuss it here.

In C ++, the pointer to an object member is not necessarily 4 bytes in size, mainly because when multiple virtual inheritance and virtual functions are introduced, some additional information also needs to be passed through this pointer, so the pointer pointing to the object member will increase, whether it is pointing to the member data or the member function, which is related to the implementation of the compiler, you can write a very small C ++ProgramVerify it. In addition, for a static member of a class (static member, which can be a static member variable or a static member function), the pointer to it is just a common function pointer, instead of a pointer to a class member, its size does not increase, and it is still 4 bytes.
Pointer operators & and *

"& And *" are opposite operations. '&' gets the address of a thing (that is, the pointer itself ), '*' gets the object (the object pointed to by the pointer) in the address ). This item can be values (objects), functions, arrays, class members (class member), and so on.

With reference to the above analysis, we can better understand & and *.

What are the advantages of using pointers?

We have discussed the nature and basic operators of pointers. Here, I want to talk about the necessity and benefits of using pointers, this will pave the way for our future use and understanding of the subsequent chapters. In short, pointers have the following benefits:

1) facilitates the use of dynamically allocated arrays.

I will explain this explanation in the sixth part of this series.

2) perform common access to multiple variables of the same type (or even similar type.

It means that a pointer variable is constantly referred to between multiple variables, which makes it very flexible to use. However, this method is also dangerous and should be used with caution: because the wrong pointer is very taboo in programming.

3) changes the value transfer feature of a function in disguise.

To put it bluntly, the pointer is used to transmit the address of a variable to the function as a parameter, so that the function can modify the variable.

4) saves the function call cost.

We can pass parameters, especially large parameters (such as structures and objects), to the function using their addresses as parameters, this saves the space and time overhead of the compiler to make copies for them.

5) dynamically expand the data structure.

Because pointers can dynamically use malloc/New to generate memory on the heap, it is very useful when you need to dynamically expand the data structure. For example, for trees, linked lists, and hash tables, this is almost an essential feature.

6) in contrast to the current computer memory model, direct access can be made based on the memory address, which makes C very suitable for some lower-layer applications.

This is also a powerful advantage of the C/C ++ pointer. I will introduce the application of this advantage in detail when I talk about the underlying operations of the C language later.

7). traverse the array.

For example, when you need to operate on the string array, think about it. Of course, you must use a string pointer to scan the string.

... There are too many, you can slowly add ^_^.
Pointer Problems

1. Problem: NULL pointer Definition

I have seen. H files define null as 0l. Why?

Answer and analysis:

This is a question about the definition of a null pointer macro. Pointers are often used in C language. Sometimes a pointer needs to be set to a null pointer, for example, during pointer variable initialization.
The NULL pointer in C language is the same as nil in Pascal or lisp. So how to define a null pointer? The following statement is correct:

Char * P1 = 0;
Int * P2;
If (P! = 0)
{
...
}
P2 = 0;

That is to say, in the initialization, assignment, and comparison operations of pointer variables, 0 will be understood by the compiler as a null pointer. As for whether the internal expression of the NULL pointer is 0, it depends on the machine type, but it is usually 0. However, in other cases, for example, the parameter prototype of a function is pointer type. If 0 is passed as a parameter during function calling, the compiler cannot understand it as a null pointer. Explicit type conversion is required, for example:

Void func (char * P );
Func (char *) 0 );

Generally, 0 can be placed inCodeIt is used in association with pointers, but some programmers (the number is still quite large! Maybe it's yours.) I don't like 0 straightforward. I think it cannot represent the special meaning of a pointer. So I need to define a macro null to explicitly express a null pointer constant. This is also true. The C language standard clearly states: "null should be defined as a null pointer constant related to implementation ". But what value is null defined? I think you have seen several methods to define NULL:

# Define null 0
# Define null (char *) 0
# Define null (void *) 0

The above definition can work on the vast majority of computing systems we use, such as PCs. However, there are many other types of computers in the world, and their CPUs are not Intel's. In some systems, the size of pointers and integers is inconsistent with the internal representation, and even the size of pointers of different types is inconsistent. To avoid this portability problem, 0l is the safest and most appropriate definition method. The meaning of 0l is: "An integer constant expression with a value of 0 ". This is exactly the same as the NULL pointer definition in C. Therefore, we recommend that you use 0l as the null value of the NULL pointer constant.

In fact, the null value is related to the operating system platform. A pointer is defined as null, which is used to protect the operating system because the pointer can access any address. However, some data is not accessible to general users, such as the core data of the operating system. When we use a null pointer to retrieve the azimuth data, the system will prompt that the data is invalid. How does the system know this ??

Taking windows 00000000 as an example, the system requires that system data is stored in a certain address range starting from the starting address of each process (0 x) in the system, and the user process cannot access it, therefore, when you use a null pointer (0) to access the system data at the 0x00000000 address, because the address data is protected by the system, therefore, the system will prompt an error (Invalid Pointer access ).

This means that the null value does not have to be defined as 0. As long as it is defined in the address space of the system's protection range, for example, it is defined as (0x00000001, 0x00000002) all play the same role, but in order to consider portability, it is generally defined as 0.

2. Problem: pointer-related programming rules & Rule Analysis

Since pointers are so important and prone to errors, is there a way to reduce the occurrence of these pointer-related problems?

Answer and analysis:

The root cause of reducing errors is to thoroughly understand pointers.

In terms of methods, certain encoding rules may be the most immediate method. Next I will introduce the programming rules related to pointers:

1) unused pointer Initialization is null.

2) Before and After allocating space to pointers, make judgments.

3) Delete the content to which the Pointer Points and clear the pointer itself.

Keep in mind that pointers are the essence of a composite data structure. Therefore, both initialization and cleanup must take into account the pointer itself (Rule 1 and 3) and the content pointed to by the pointer (rule 2 and 3) these two aspects.

Following these rules can effectively reduce pointer errors. Let's look at the following example:

Void test (void)
{
Char * STR = (char *) malloc (100 );
Strcpy (STR, "hello ");
Free (STR );
If (STR! = NULL)
{
Strcpy (STR, "World ");
Printf (STR );
}
}

What are the results of running the test function?

A:

Tampering with content in the dynamic memory area is unpredictable and dangerous. Because free (STR); then, STR becomes a wild pointer, if (STR! = NULL) the statement does not work.

If rule 3 is kept in mind, add a statement after free (STR:

STR = NULL;

Then, this error can be prevented.

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.