C51 study notes, array and pointer programming

Publisher:落霞与孤鹜Latest update time:2018-01-03 Source: eefocusKeywords:C51 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

Finally, we are talking about pointers. Pointers are the essence of C language. Without pointers, many low-level operations of C language will not be completed. It is also because of the existence of pointers that C language does not look so advanced, because the object of pointer operation is the memory address. If you want to operate pointers skillfully, you must consider hardware-related things such as memory. Of course, you don’t need to know too much. However, the data structure level still needs to be passed. I don’t know much about data structures, so I won’t say much. The relationship between arrays and pointers is so complicated that I have to write this note according to the book.

1. Arrays are not equal to pointers

In C language, array operations are performed in the same way as pointers. However, it is important to remember that arrays are not equal to pointers. For a one-dimensional array a[] and a pointer p=a pointing to an array, the biggest difference between them is that the array method uses the array name a (which is also the first address of the array) to directly access and operate the array, while the pointer method uses the pointer name p to indirectly access and operate the array. In most cases, their operation results are the same, but there are exceptions.

If we define a pointer p outside the file, int *p=a (a is an integer array). When using p in the file, we need to use extern to declare it, indicating that p is an external variable and is defined externally. If we declare it as a pointer extern int * p and then use it, there will be no problem. But if we declare it as an array extern int p[], problems will arise. The compilation system will use array methods to operate on pointers. In other words, when we want to get the value of *p, that is, *a, a[0], because the system treats p as the first address of the array, *p cannot get a[0], but the address value stored in p, that is, the address of a[0]. In this case, the extern declaration must match the definition.

The most fundamental difference between the direct access mode of arrays and the indirect access mode of pointers is that arrays are not equal to pointers. Arrays are usually used to store a fixed number of elements of the same data type. The memory occupied by arrays is implicitly allocated and deleted. Arrays store data, and each element in the array has a unique and clear variable name to identify the data. Using arrays, data can be directly accessed, that is, a[i] simply obtains data with a+i as the address. Pointers are usually used in dynamic data structures. Pointer variables store the address of data (including the address of variables and non-anonymous data). Using pointers to access data adopts an indirect access mode, that is, first obtain the content of the pointer, use it as the address, and then extract data from this address. If the pointer has a subscript, p[i] first gets the content of pointer p, then adds the content of pointer p plus i as the address to extract data. Pointers can point to anonymous data, so you must learn to use pointers to operate anonymous memory. The functions related to memory space in C language are mal LOC (), free().

When defining a pointer, the compiler does not allocate memory space for the object pointed to by the pointer, but only allocates space for the pointer itself, unless a character pointer (which must point to a character type) is defined and initialized with a string constant. In fact, even in this case, it can be regarded as the compiler allocating memory space for this string constant, and then allocating space for the character pointer itself, and making the character pointer point to the first address of the string constant. In ANSI C, the string constant created by the initialized pointer is defined as read-only (? I tried this with turbo C, and it seems that it can be modified). Arrays can also be initialized with string constants, but unlike pointers, arrays initialized with string constants can be modified. The reason is very simple. The array initialized with a string constant is originally a character array, and each character has a certain variable name corresponding to it, so of course a single character can be modified. The string constant created by the initialized pointer is actually anonymous data. If you assign the character pointer pointing to the string constant to another address, this string constant will obviously never be found again.

It can be seen that arrays and pointers are different when processed by the compiler, and their representations at runtime are also different, and different codes may be generated. For the compiler, an array is an address, and a pointer is the address of an address. Therefore, when declaring an external array or defining an array (because the definition of an array must allocate memory space), a pointer cannot be used to replace an array.

Also, a reference to an array cannot be replaced by a pointer to the first element of the array in the following cases:

1. The array name is used as the operand of sizeof(), because the size of the entire array is needed, not the size of the first element pointed to by the pointer;

2. Use the & operator to get the address of the array. The main purpose of the & operator is to implement address-by-address call. The pointer itself is the address, so using & on the pointer is meaningless.

3. The array is initialized by a string constant. This has been mentioned above, so I won't say more. The array initialization by string constant must be done in one go, and cannot be divided into two statements. In other words, string constants can only be used to declare and initialize arrays, and string constants cannot be used to assign values ​​to arrays. This is because in C language, an array can only be initialized when it is declared (there is no reason for this, perhaps because the array name is an immutable left value), and you cannot assign values ​​to the array name, but only to the array elements one by one.

4. The array name is an unmodifiable left value. Its value is the address of the first element of the array and cannot be changed.

2. When are arrays and pointers the same

Most of the time, arrays and pointers are interchangeable.

1. Except for some special cases, the array name in the expression (the array is in use, not in the declaration) is a pointer

Suppose we declare: int a[10], *p, i=2;

You can access a[i] by:

a[i];

*(a+i);

p=a ; p[i] ;

p=a ; *(p+i) ;

p=a+i ; *p ;

In fact, array references such as a[i] are always rewritten by the compiler as *(a+i) at compile time. So, like addition, the operands of the subscript operator can be interchanged (a[i] and i[a] are both correct and equivalent).

The compiler automatically adjusts the step size of the subscript value to the size of the array element. Before performing the addition operation on the starting address, the compiler will be responsible for calculating the step size of each increase. This is why pointers always have type restrictions and each pointer can only point to one type.

2. Array subscript is always the same as the pointer offset

The array subscript is always the same as the pointer offset, so the programmer can use the pointer to access the array, thus bypassing the subscript operator. In this case, the array subscript range check cannot detect all accesses to the array. Therefore, C language does not perform subscript range check. But when we write programs, we must be careful not to cross the boundary.

Pointers are not faster than arrays when dealing with arrays. The fundamental reason why C language rewrites array subscripts as pointer offsets is that pointers and offsets are the basic models used by the underlying hardware.

3. Array names as function parameters are equivalent to pointers

Equating arrays and pointers as formal parameters is done for efficiency reasons. In the declaration of a function parameter, the array name is interpreted by the compiler as a pointer to the first element of the array. The compiler only passes the address of the array to the function, not a copy of the entire array. Implicit conversion means that the following three function definition forms are identical:

fun(int *p){...}

fun(int p[]) {...}

fun(int p[10]) {...}

It is legal to use an array or a pointer to the first element of an array in a function declaration or call.

Note the meaning of the first element here. This first element can be a numeric variable, a character variable, an array, a structure, or a pointer.

Conclusion

An array is not equal to a pointer, but an array can be equivalent to a pointer; a pointer is always a pointer, and a pointer can never be rewritten as an array. You can use subscripts to access pointers, usually when the pointer is a function parameter, usually when the pointer points to an array element.

When declaring and defining externally, arrays cannot be equated with pointers. Except when arrays are used as function parameters, the definition and declaration must match.

Arrays are basically interchangeable with pointers when used. a[i] is always interpreted by the compiler as *(a+i).

When used as function parameters, arrays can be interchanged with pointers. The compiler always modifies the array of function parameters into a pointer to the first element of the array. In fact, what is obtained inside the function is a pointer.

C language does not actually have multidimensional arrays. Only array elements are arrays of arrays. When a multidimensional array is used as a function parameter, the pointer type passed is a pointer to the array.


Keywords:C51 Reference address:C51 study notes, array and pointer programming

Previous article:Application of Operators in C51 Programming
Next article:The Relationship between Arrays and Pointers in C51 Programming

Recommended ReadingLatest update time:2024-11-16 14:44

Keil C51 compilation error warning solution accumulation
1. Warning 280: 'i': unreferenced local variable Explanation: The local variable i is not accessed in any way in the function. Solution: Eliminate the declaration of the variable i in the function. 2. Warning 206: 'Music3': missing function-prototype Explanation: The Music3() function is not declared or not declared e
[Microcontroller]
C51 interrupt counter
#include reg51.h #define uchar unsigned char #define uint  unsigned int  #define long unsigned long uint tc; static uint i; fly ledbuff ; fly ledchar ={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; void init_en() { EA = 1; ET1=1; ET0=1; TMOD = 0X51; TH0 = 0XFC; TL0 = 0X67; TR0=1; TR1=1; } void clac(u
[Microcontroller]
C51 interrupt counter
AT24C01-AT24C256 general source program (C51)
 It is said to be a universal source program for AT24C01-AT24C256, but in my experience, this source program is only suitable for AT24C04-AT24C256. /*Sample: /*main(){    ... /* ReadMem(l,x,y); /* Read. l is the device number of this access. Different chips are assigned different Device number,             x
[Microcontroller]
C51 MCU Study Notes - IO Expansion (Serial to Parallel) Experiment - 74HC595
Purpose: To control the LED matrix to display in a row loop through the 74HC595 module. Compiler software: keil5 process: (1) First define the 74HC595 control pins and the dot array control port //Define 74HC595 control pins sbit SRCLK=P3^6; //Shift register clock input sbit RCLK=P3^5; //Storage register clock
[Microcontroller]
C51 MCU Study Notes - IO Expansion (Serial to Parallel) Experiment - 74HC595
MCU continuous key detection C51 program
I had nothing to do these days, so I dug out my old simulators and programmers and found a few STC12c2052s. I wrote a small program to modify the relay function, which mainly implements: 1. Press the transmit button three times in 5 seconds to turn on the relay. 2. After the re
[Microcontroller]
C51 MCU IIC bus communication protocol and simple application examples
First of all, we need to distinguish the meaning of communication protocol and the meaning of "信" and "讯" in communication protocol. "Communication" refers only to data communication, that is, the end-to-end transmission of data through computer network systems and data communication systems. The "信" in communication
[Microcontroller]
Homemade MCU 16…Convert text or graphics into C51 fonts used on LCD
In this lecture, I will talk about how to use the font extraction software to convert graphics into data. Many people have repeatedly asked me this question, so I will explain it in detail!   There are many font extraction software. Some can only convert text into font data, while others can convert text into fonts an
[Microcontroller]
MCU C language tutorial: C51 operators and expressions (pointer and address operators)
When we studied data types, we learned about pointer types, and we know that it is a variable type that stores the address of another data. Pointer is a very important concept in the MCU C language, and it is also a difficult point in learning the MCU C language. Pointers will be explained in detail in Lesson 9. Her
[Microcontroller]
MCU C language tutorial: C51 operators and expressions (pointer and address operators)
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号