The C language pointer tutorial can be continuously updated without basic introductory chapters

Foreword:

The full text starts with virtual memory, and it is very simple to talk about this inadvertently swiping up: virtual memory

This article only talks about C pointers, and also involves pointer usage, such as "Why arrays are related to pointers", but it will not go into details about arrays, functions, compatibility, implicit conversion, etc. It will only give a simple explanation, if Giving a detailed explanation in this article will only increase the difficulty of learning for everyone, and it will also cause trouble for myself. If the "flow" of this article is considerable, I will also base it on the cppreference website and the content of the C standard (including C98 to C20 ) . Refer to the corresponding articles after sorting out in my own words, and there will also be a small part of the C23 draft content. If C23 and the new standard are used, I will mark them in the article.

For newcomers, this article: "Help you understand the wrong cognition before the change...", for those who get started, you can also read it to deepen your impression. For the big guys and practitioners who want to point out the mistakes in the article, I (CSDN: Starry Sky Long Night i) The first tutorial article was published, and it turned out to be answered in the group.

Do not redistribute without permission.


Directories: Place when done.


Chapter 1 Getting Started with Pointers (Must Read)

1.0 theory (all fit):

 

Presumably everyone has been tossed by pointers and arrays when learning C, especially some "books/videos, even think yourself" equates pointers to arrays. Only in this case will it experience the implicit conversion of the pointer to its first element that is not an lvalue (constant) .

Note supplementary knowledge points:

①Only in a few special cases will it experience the implicit conversion pointing to its first element that is not an lvalue (constant) pointer.

②A pointer is an object type that refers to a function or another type of object, and qualifiers can be added. A pointer can also refer to nothing, which is indicated by a specific null pointer value.

③ Null pointer ≠ wild pointer, please do not use the indirect operator-dereference for these two pointers.

Note, this article agrees: T is a hypothetical class. Readers don’t need to think about this class. It’s all about handling it. When it’s actually used, readers are asked to use the C type instead.

 

1.1 Memory and Objects

Basic knowledge pointer syntax: type * pointer name;

First look at the definition statement:

T num=10; //T type variable

/*T type pointer initialized to null pointer*/

T* needle=NULL;

 

The statement above defines the following "memory model" (actually complicated, the ... number means omission, in fact, it is also possible that two objects are close to each other, or there may be a difference of n memory):

 

7974b19b66aa4ad4b1e09f15dae5e329.jpg

According to this picture, you can find that the variable name has a matching address. It is one of the features provided by the high-level language, and the details are handled by the compiler and the system... because this can save time and effort. It is very troublesome to remember the address, such as:

If you set up 10 8-bit "memory addresses", such as an 8-bit: (010101010), you may remember it, but for 100, you may write it down in your notebook, and if you use more, use two-to-decimal or sixteen: 0xF7d, 0xF6d...

But if we don't think about how to form a "16-bit memory address" (hint: not absolute int class size)⁰, for example, a "16-bit memory address" (01100010 00011101)

How do you remember this "16-bit memory address"?

Don't say ten light one is very troublesome to remember, and in reality, do you only use single-digit int objects in your program? It may be too small, and in order to solve integer overflow (when the int cannot be stored), you will choose to use long, then the long type may be "32-bit memory address", and if it exceeds your use, it may be "64-bit memory address" long long....

So a person can't remember it, so there is a name composed of English letters instead of "memory address", and isn't it more convenient? Of course, Chinese is better for us, but C statements are composed of English letters. Of course, it is not impossible to use Chinese, but it is not recommended and it is off topic. (Note (briefly speaking): These details are a certain abstraction given by the OS and compiler, and the abstraction given to us by the C language is its syntax).

 

And there are several advantages: the "memory status" will change with the system, platform..., even if the same "memory" is moved to your program, can you guarantee that the memory is not occupied by other programs/hardware, and Every time it is turned on and off, it will "regenerate the memory address table...", and there are still many reasons that I won't go into details, and it is almost beyond the outline. (This is also an abstraction given by the OS, which is easy to understand and use, compared to direct operation)

Summary: In order to make it easier for people to learn, the geniuses invented this method, using English letters instead of operating addresses, letters instead of memory addresses (machine: binary address, human view: corresponding to hexadecimal) let the compiler handle, memory management and operation Wait for the system to process. ¹


Notes: ⁰ not absolute int class size:

Also because the standard doesn't define absolutely how big the type is, the standard just ensures that:

……sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

Can you understand that int may be larger than short or equal, and it will be different if you don’t use bit 4, 16, 32, or 64. Even on the same bit platform, it will also be different because of the system, compiler, etc. This is not detailed (again It’s almost beyond the outline, and if necessary, I will publish another issue dedicated to this).

¹: Supplementary knowledge for all content under the picture in Section 1.0: These methods do not affect the hardware, and the hardware still uses addresses to access memory locations.

Extra words: The concept of abstraction is very important, and it can be said to be more practical than knowing the low-level. (I plan to publish an article explaining the abstract image to Jane, but I don’t have time recently)


 

1.1 Pointer basics①

Continuing the above two sentences, the next paragraph is:

needle=& num; // Assignment, let point to T type num

In this sentence & is an indirect operator, which means to take the address and take out the address of the object.

Memory model:

f7fd9f18cf6a42dcbcd5b0059231aac4.jpg

 It can be seen that: the inside of need → points to the outside of num, this is called pointer pointing to num, or the address of num is stored inside the need pointer.

 

Summarize:

T num=10; //T type variable

/*T type pointer initialized to null pointer*/

T* needle=NULL;

needle=& num; 

All of the above statements are:

①Create T-type needle and num objects, and * determines that the object is a pointer, and T type determines the T-type address value that the object can store.

②Assign NULL to its needl pointer to make it a null pointer (no pointer dereferencing such a pointer will cause undefined behavior). This behavior is called "assigning an initial value" when assigning a value when declaring a definition.

③ Next, use the indirect operator & to assign the address value of the T variable num to the needle, so that the needle points to num.


1.2 Pointer basics②

The previous section 1.1 introduced the "one heavy" pointer, how to point (storage), the address named num, and NULL. This section uses the above content to expand and how to use it to talk about pointers.

1.2.0 dereference pointer:

In the previous section, the & indirect operator-function: take the address, this section introduces his relatives:

*needle;

In this sentence, * is an indirect operator, which means dereferencing, dereferencing the address of the object, and the value at the address.

Look at the program segment:

T num=10; //T type variable

/*T type pointer initialized to null pointer*/

T* needle=NULL;

needle=& num; 

printf("num address:%p丨num stored value:%d\n",&num,num);

printf("needle pointer address:%p\n",&needle);

prinrf ("needle stored value:%p\n",needle);

printf ("needle stored value dereference: %d", *needle);

Possible results of execution:

num address: 0xa59ebba4丨num stored value: 10

The address of the needle pointer: 0xa59ebba0

Needle stored value: 0xa59ebba4

The value stored by the needle is dereferenced: 10

According to the results, it can be found that the num address and the address stored in the needle are the same (as discussed in Sections 1.1 and 1.0), and the needle pointer is initially a null pointer (NULL) and then assigned the address of the num object, which means that the needle points to the address of the num object (0xa59ebba4 ), and the pointer itself also has its own address (0xa59ebba0).

Dereferencing the needle will show the value of num, please think about it in combination with 1.0-1.1, why, if not, please combine the model diagram and try drawing yourself.

Try to draw by yourself, you must have your own understanding, other people's understanding is always someone else's understanding, you can only use it simply, but you don't understand him.

 

Note: It can be observed that the difference between 0xa59ebba0 and 0xa59ebba4 is 4, but the address will be different. Like 1.0, it may be continuous or there may be a difference of n, and it will be different on different platforms, but the value stored in the num address and needle must be The same, because the needle pointer stores the num address, see 1.0 for details.

*There is an implicit conversion in this code, which involves (void *) which will be discussed later.

1.2.1 "In-depth" understanding-topic:

If you have the above knowledge, it is better to do the questions directly. Please think about it. If you can’t understand it, you can draw a picture, or try typing the code. (Answers are at the end of this question)

①Please think if we change the value of num, will the needle pointing to num change?

For example num=1;

②Please think about if we change the value of needle, will num change? Who does this needle point to, and what is the dereference value of needle?

For example

T i=0;

needle= & i;

③Please consider the i value, num value, dereferenced needle value, and needle point after the following operations.

needle= & num;

*needle =10;

needle=&i;

i=5;

④ Please think about the following mistakes and point out the corrections (note that nu is a "local" variable).

I don't;

num=1,i=9;

needle=NULL;

 

needle=i;

printf ("Variable i address%d\n", &needle);

num=nu+(*needle);

 

printf ("%d+%d=%d",*i,nu,num);

 

result:

variable i address 0x...

9+5=14

Answer:

Click me or you can: https://blog.csdn.net/asd2387/article/details/129107668 Please don't blame me for making fans visible.

 

 

 

Please do not read below, it is an outline for now


1.3 const qualifier

const is a keyword of C statement, which belongs to a kind of qualifier. From now on, this article will be referred to as cv qualifier, because there is another qualifier called volatile (one that restricts compiler optimization, which is generally not used and will not be discussed).

 1.3.0 const basis - object

If you have a basic understanding of const semantics, please skip this section (1.3.0) and only talk about simple usage.

Variables defined by const can only be read, please see the program:

const int a=0;

int const b=1;

These two variables can only read unchangeable values ​​when the entire program is running. If they are modified, the compiler will report an error, such as (wrong):

a=5;

i=a;

a=i;

The above three sentences are not allowed, because const defines the variables a and b as "constants", which can only be read or their addresses are taken (optional). Note that the reasons for "constants" in double quotes are shown in 1.3.2 Advanced.

1.3.1 const basis - pointer

For those who understand const and pointers, please skip this section (1.3.1)

int i=1;

const int*  q=&i;

int const*  w=&i;

The above two statements express the same semantics, and the pseudocode explains:

Read-only integer class* Pointer q Assign i address;

Integer class read-only * Pointer q assigns i address;

Is this understandable? Is it a bright spot? , if not, don’t worry, then disassemble + auxiliary words to explain:

read-only *pointer to q 

Yes, it is to define the sentence "*pointer" as read-only! That is to say, the pointer dereference operation is defined as only readable!

That is to say, the following usage is wrong:

*q=2;

*w=i;

*q=*w;  

#Most people may have read other articles like me. The above two pointer definitions probably talk about setting i as read-only. I don’t agree with this, because I only talk about C syntax. I think the const qualifier It is only limited to the pointer, instead of skipping the pointer and setting the object he points to as const, because it is obvious that i can be directly modified.

 

int* const r=NULL;

 Integer class * pointer q read-only assign NULL;

 

int* const i=NULL;

 

1.3.2 advanced const (recommended)

Update 1.3.1 update↓

const semantics apply only to lvalue expressions, telling the compiler that the object is placed in read-only memory.

Detailed explanation:

Whenever a const lvalue expression is used in a context that does not require an lvalue, the const qualifier is lost!

const int* const CannontMaodify = NULL;

The CannontMaodify cannot be modified directly, unless the CannontMaodify is modified by using other non-c-qualifier pointer objects, and the indirect modification is modified by a pointer.

Proof Program Link: Personal Essay

 

 

 

1.4 Function parameters and value passing

Next, let’s talk about the relationship between function parameters and pointers. My chapter focuses on practicality and simplicity, so I will talk about function parameters and pointers first. Most books should start this section with arrays and pointers.

    If you don’t learn the function content, don’t worry that the function will not be explained in detail. In fact, there are many functions in detail. I only teach you how to use pointers for simple function parameters.

 

 

 

 

 

 

 

 

 

1.5 pointers and arrays

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/asd2387/article/details/128911180
Recommended