Detailed explanation of arrays and pointers in C language

The original address is: Detailed explanation of C language arrays and pointers

++++++++++++++++++++++++++++++++++++++++++

This article is the original of this site, welcome to reprint! Please indicate the source for reprinting:

http://blog.csdn.net/mr_raptor/article/details/6844691

++++++++++++++++++++++++++++++++++++++++++

 

       Many students say, "Teacher, I'm dizzy when I see the pointer !" To be honest, I've seen blood sickness, motion sickness, and pointer dizziness. This is the first time I've heard of it!

       Let's first analyze the principle of motion sickness, and then compare why the pointer is dizzy.

       Motion sickness is because an organ in the ear is too sensitive to external vibrations, causing the body's adjustment function to be disordered and the system to not work properly. After a long time, I know I get motion sickness, so when I see buses, TAXI, trains, and bicycles, I get dizzy! This kind of disease will get bigger, and it will rise to a mental illness. This can be cured. We all understand the above truth, how to overcome motion sickness? You can't avoid doing a car, you have to face it. How to overcome motion sickness is very simple. First, you need to work hard. "Oral is not as good as convincing." Always try to make a car with little shaking, preferably listening to MP3, which can reduce the psychological sensitivity to motion sickness. After a long time, I gradually overcome the psychological effect, and then it will rise to the stage of root control. I will try to challenge the bus, TAXI, and boat.

       The above are all personal opinions. When you go to college, if you don't learn computer science, you will study medicine!

       When we came back, we started to treat the disease "Dizzy Pointer". In fact, many students fainted pointer because of their poor foundation (poor physical fitness). The students who have not compiled a program for 4 years) are wrong, and they form a fear. In fact, the C pointer is very flexible, and its requirements for students are relatively high. To put it bluntly, it requires some basic principles of computer composition. If there is any Then, look back at the pointer, So easy!

       Let's start with the "heart attack".

 

1. Dizzy pointer, Tang-style remedies 1: "Throwing stones to ask for directions"

#include <stdio.h>

int main(void)

{

       char* str = "ABCDEFGHIJKL";

       int* pInt = (int*)str;

       printf("%c\n%c\n",*(str+1),*(char *)(pInt+1));

       return 0;

}

       If you answer the above program with EASY answers, then your skills are already good! It is estimated that the heart disease is gone, and you can enter the stage of taking medicine and maintenance (do the question).

If the above questions seem to be particularly strenuous, it seems that your dizziness is not light, and you need to be cured. Otherwise the problem will be serious.

 

Based on the above small test, enter the second method of Tang style: "regulating qi and calming the mind"

       Let's first look at laying the foundation for C pointers. Before that, let’s review variables and constants. Some students will ask, why is this? I can only tell you that you fainted the C pointer because you didn’t pay attention to the problem from the beginning, or you ignored the problem. The seriousness has led to the current situation. There is no way to do this. Chinese education does not pay attention to this aspect. To be honest, many of the C language speakers in colleges do not talk much about variables and constants, which is very XXX. We start treatment.

 

  •  Constant: A quantity whose value does not change is called a constant. Constants, also known as literals, represent constants. They can be classified with data types, such as: integer constants, floating-point constants, character constants = =, constants can be directly referenced without being defined and initialized .

Constants are divided into: direct constants and symbolic constants.

Direct constants are also called: literal constants. such as 12, 0, 4.6, 'a', "abcd"

Symbolic constants are defined as macros: #define PI 3.14

Features: The value of a constant does not change within its scope and cannot be assigned again. It is used as an immediate value when it appears. That is to say, it can only be accessed and read, but cannot be written or assigned.

 

  •  Variable: A quantity whose value can be changed is called a variable. A variable should have a name and occupy a certain location in memory. Variables must be defined before they can be used .

 

  •  Variable name and variable value:

The variable name is when the variable is declared, the name is bound to an address in memory . The corresponding memory area can be found directly by the variable name, or its memory area can be found by the address. Hence the rationale for introducing pointers.

The value of a variable is a binary sequence stored in the memory area corresponding to the variable. When the variable is declared as integer, the binary sequence of memory regions is translated in integer form. For example: int a = 97; It is stored in the binary form of 97 in memory, and when used, it will be expressed in decimal form. The same char a = 'a'; the ASCII code of a is 97, which is also stored in the binary of 97. When used, it will be displayed in the form of the character a.

If the variable is a pointer variable, then the binary sequence in the pointer variable is translated into an address,

for example:

       int a = 10;

       int * p;

       p = &a;

The value of the pointer variable p here is the address of a (p = &a), what is it? Look at the picture below:

Declare a variable a, which is an integer, and is assigned a value of 10 (its value is translated into an integer). To form this kind of thinking, you will know the benefits of doing so after a long time, and declare a pointer variable p , it is of type Int (the address it points to needs to be installed with Int), and then the address of the a variable (ox2c406b24) is given to p, pay attention here. Now there are two ways to access the value in a (in fact, there are originally two), one is through the variable name a (bound), the other is through the address ox2c406b24, the address ox2c406b24 is given to p, the p pointer variable ( pointer Variables are variables, this thinking is very important ) what is stored in it is ox2c406b24 (the address of a), then now you can access a through:

       printf("%d\n", a); //By variable name

       printf("%d\n", *p); //through pointer variable

If you understand everything above now, then you have signs of dizziness pointers getting better, just signs, (signs だけです^_^). Now check if it really improves:


1、

char ch = 'a';

int a = (int)ch;

printf("%d %c\n", a, ch);

what is ch? what's in ch? what is a? What is in a? print what?

2、

int add = 0x123456;

int * p = (int*)add;

what is add? what is in add? What is P? What's in P? what is *p again?

Hey, are you dizzy? Don't panic, come again. . .

3、

#define PI 3.14

int a = PI;

printf("%d\n", a);

Is there any problem with the above program?

4、

#define PI 3.14

printf("%d\n", PI);

Is there a problem with the program?

5、

#define PI 3.14

int a = PI;

PI = 1.85;         

int b = PI;

printf("%d%d\n", a, b);

Is there a problem with the program?

 

It's almost a headache, right? It's okay, this is medicine, and good medicine is like this.

the last one:

6、

char *str = "abcdef";

printf("%s\n", str);

*str = "fedcba";

printf("%s\n", str);

str[2] = 'C'; //modify the third character to uppercase

printf("%s\n", str);

Is there a problem with the program?

Well, this is the end of the first party, the old Chinese doctor will have a rest.


The medicine above is more powerful, young people should focus on the taste. Now for you some antidote:

1. Mainly test type conversion and whether the understanding of variables is in place.

2. Is the understanding of the value of the variable in place?

3. Is the understanding of constants and macro substitution in place?

4. Is the understanding of macro substitution in place?

5. Can the value of the constant be modified?

6. Can the value of string constants be modified?

Through the above, we can learn the following content, the key points, write down, and take the test (this is very familiar in school, but XXX is very irresponsible):

       1. No matter what constant, its value is fixed for compilation and cannot be changed.

       2. The value in the variable has nothing to do with its data type. It is just a binary sequence. Don't think how smart the computer is. It only knows 0 and 1. However, this pile of 01 is limited by its type. Meaning, the type is integer is its value, the pointer address type is an address in memory, and the character type is the ASCII code represented by its unsigned integer.

      3. A string is a constant (the character pointer points to a string, not an array , the difference between an array and a pointer is at the back), its value cannot be changed, char * str = "abcdef"; this line of code means to tell the compiler Device: Old editor, I have a drawer here (pointer variable str), you can find me a room (memory space for storing strings), and after you find it, give me the key and put it in this drawer. The old editor went to the room manager, and after finding it, he asked: Is there any room available? If there is one, give me one. The first buddy wants to open a room. The room manager will check the occupancy of the room (memory management), and finally said, there is a room here. It's the boss's room. If you don't use it first, you'll be fine. Don't mess with the things in it. If you move, it's estimated that your buddy will be killed. The boss is a triad, but you'll be fine. So, the editor gave me the key of the boss's room and put it in the drawer (pointer variable str), so I opened the drawer (pointer variable), took out the room (memory space) key (pointer), and went to open the room, the editor told me , don't mess around, use it for nothing (read), you must not destroy the structure inside (modify the data content), if you mess (modify the data), it will cause trouble (segmentation fault), and then you will be KILL (abnormal termination of the program) ). If there are two people, it will be Double kill, and the boss will GOD LIKE.

 

After understanding the difference between constants and variables, it will be easier to learn later! Let's take a look at the twin brothers of pointers, arrays. In general, many people with motion sickness are also airsick and seasick. Therefore, those who are dizzy with pointers will generally dizzy arrays.

 

  •  Arrays: Let’s read the words first, count data, groups are groups, and groups composed of data are called arrays (for those who learn computers, not only do you need to learn computers, but also languages, and occasionally medicine, if you often If you look at computer books, if you look at the books written by Taiwanese, there are a lot of classical Chinese in it. We are not as good as the Taiwan compatriots at this point. Therefore, other people's computer experts, the world's electronic foundry, Taiwan accounts for the vast majority. ratio).

There are several characteristics of arrays that must be paid attention to. When you see an array, you must think:

1. The data types in the array are the same, and the members in the group must be the same. A horse stands in a pile of donkeys, and there is no distinction between donkeys and horses. The computer also talks about "harmony". Let's take a look at the basic types of data: int float double char These are basic types, so they can exist in arrays like: int a[10], float f[10], doule d[10], char str[10]; Each of them has 10 elements, and each element is of the type declared before it . We learn to be embedded, we can’t just see the superficial things, we have to see to the end, good things are only applauded when they are gone, and good things are only good if others don’t know about them. In fact, the array is allocated continuously in memory, as shown below:

A char type array a is defined, which has 6 elements, namely 'A', 'B', 'C', 'D', 'E', 'F', which are stored continuously in the memory, each elements occupy one byte. Strongly condemn those who take 'A' as "A", the former is a single character, the latter is a string, despise those who ask "what's the difference between a character and a string?", don't know the difference between a character and a string , have you ever eaten lamb skewers? Can a single piece of mutton be called a string? A string of multiple pieces of mutton is called a string, so the character is single, and the string can be an array of multiple characters (with an ending symbol \0 at the end). It's called kebabs, a string is copied, it's called a copy string, how can it be so easy to learn computer, if I open a school, I have to have a physical examination, test eyesight, measure height and weight, ...., measurements, etc., no PASS.

       Look carefully at the above picture, each character has an address, their span is 1 (byte), each element of the array can be accessed by subscript, subscript (index, for loop variables often use i because This thing) is actually his position in the array, that is, his number, pull 10 people over, report the number, 1, 2, 3..., but, the subscript of the array in C language is from 0 At the beginning, the smallest unit that can be accessed in the computer is the byte, that is, the address can only be found in bytes, and it cannot be more precise. The array name a is the same as the variable name in principle. It is bound to the first address of the array at compile time. a is the first address of the array. The variable name and the array name are actually code names that are convenient for people to remember. After the code is disassembled, there is actually no variable name. Recall that there are two ways to access data. Since the disassembled code does not have a variable name, the only way to access the data is the address. Each element in the array can be regarded as a variable (recall the characteristics of variables), so it can be read, written, modified, as long as you don't dismantle the room (memory space) , no matter how toss. The address of each element can be calculated by the offset of the first address (remember the word offset, not in the fourth level). This offset is simply a subscript. For example, in the above picture: 'C' is located at address 0x28c5, and the offset from the first address 0x28c3 is 2, then a[2] can also access 'C'. Note that a represents the array , which represents the first address of the array , Represents the address of the first element of the array , these " three represent"Be sure to remember. What about a+1, a is three representatives, then is it the first representative, the second representative, or the third representative? The a here should be the meaning of the first element address. The meaning should be &a[0], a+1 is the arithmetic operation of an address, and the array is a one-dimensional array, each element in the array is a character, a+1 is the address 0x28c4 of the next element of a current address 0x28c3 (Combined with the figure), that is, the address of 'B', if a is the name of a two-dimensional array, then the two-dimensional array is understood by the compiler as a one-dimensional array, and each element in the one-dimensional array is a one-dimensional array. The dimensional array is a bit messy, don't panic, repeat it, look at the picture below:

a is a two-dimensional array with 3X4=12 character elements, and the compiler considers it to be a one-dimensional array with three elements, a[0], a[1], a[2], each An element is an array containing 4 characters, then a+1 is the address of &a[0], a[0] is a one-to-one array, take the address of an array, add 1, it must be the next The address of the array is the a[1] picture above, then at this time, its address increase is no longer 1, but the number of columns is 4, which means the length of the element (one-dimensional array) in the two-dimensional array a. .

       Back to the previous picture: a[5] - a[3] = ? The operation of the address, the relative offset of the element is also calculated here, the result is of course 2, although the result of 0x28c8- 0x28c6 = 2 is also 2, but the meaning is not In the same way, if the array type is changed to int a[10], then a[5] - a[3] is still 2, not 8. This is just right to use subscript subtraction.

       Therefore, we can summarize that when adding and subtracting pointers, it depends on the type, the dog depends on the owner, and the pointer adds and subtracts depending on the type. The value of the operation is n*sizeof (type) , such as: adding 1 to the character address, in fact, the address addition is also sizeof(char) = 1, add 1 to the integer address, add sizeof(int) = 4 to the address, add 1 to the address and add sizeof(structure) to the address in the structure array.

 

       It can be seen from the above analysis that arrays are very similar in many ways. In fact, when the compiler treats the array as a pointer, there is no way. The compiler only recognizes the address, and the variable name is always The compiler defies that.

       Look at a program diagram:

The term program map is my own creation, because many things are unclear and unclear, and one map is all done.

What is the result of the above execution? It is already clear. break.

       The result of the above example is: B and E

++++++++++++++++++++++++++++++++++++++++++

This article is the original of this site, welcome to reprint! Please indicate the source for reprinting:

 

http://blog.csdn.net/mr_raptor/article/details/6844691

++++++++++++++++++++++++++++++++++++++++++

 


Please indicate the address of this article when reprinting: Detailed explanation of arrays and pointers in C language

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324072456&siteId=291194637