当前位置:网站首页>Fundamentals of C language -- similarities and differences between arrays and pointers
Fundamentals of C language -- similarities and differences between arrays and pointers
2022-06-30 15:17:00 【Alien-Hu】
List of articles
1. The difference
- The array name cannot be changed , The pointer to the array can be changed .
- Pointer to string , The string cannot be changed ; The string defined by the character array , Characters can be changed .
- When finding the length of an array , The array length can be obtained by borrowing the array name , You can't get the array length by borrowing the pointer .
1. The array name cannot be changed , The pointer to the array can be changed
Traversal mode 1 :
#include <stdio.h>
int main(void)
{
int a[5] = {
0, 1, 2, 3, 4 }, * p = a;
char i;
// Array traversal mode I
for (i = 0; i < 5; i++)
{
printf("a[%d] = %d\n", i, *p++);
}
return 0;
}
a[0] = 0
a[1] = 1
a[2] = 2
a[3] = 3
a[4] = 4
Array traversal mode I : Use the pointer to traverse the array elements ,*p++ Equivalent to *(p++), That is, the address pointed to by the pointer moves back one unit at a time , Then take the value on the address . One unit here is sizeof(int) Bytes .
Traversal mode 2 :( error )
#include <stdio.h>
int main(void)
{
int a[5] = {
0, 1, 2, 3, 4 }, * p = a;
char i;
// Array traversal mode 2
for (i = 0; i < 5; i++)
{
printf("a[%d] = %d\n", i, *a++);
}
return 0;
}
- error: value required as increment operand
- Because the array name cannot be changed , Using the autoincrement operator autoincrement will change its direction , It's not right , Array names can only point to the beginning of an array .
Traversal mode 2 :( correct )
#include <stdio.h>
int main(void)
{
int a[5] = {
0, 1, 2, 3, 4 }, * p = a;
char i;
// Array traversal mode 2
for (i = 0; i < 5; i++)
{
printf("a[%d] = %d\n", i, *(a+i));
}
return 0;
}
- *(a+i) So the pointer passes through the offset , Find the specific value , Instead of changing the pointer itself
- *(a+i) And a[i] It is equivalent.
2. A string of 2 Initialization methods
// String definition method 1
char str[] = "happy";
// String definition method 2
char *str = "happy";
- Mode one : The characters in a string can be changed . If you can use something like str[3]=’q’ Such a statement to change the characters . The reason is that : The strings defined in this way are stored in the global data area or stack area , It's readable and writable .
- Mode two : The characters in a string cannot be changed . The reason is that : The string defined in this way is saved in the constant area , It's not modifiable .
3. The group name can find the length of the array , The pointer cannot get the length of the array
#include <stdio.h>
int main(void)
{
int a[] = {
0, 1, 2, 3, 4 }, * p = a;
char len = 0;
// How to find the length of an array
printf(" Mode one :len=%d\n", sizeof(a) / sizeof(int));
// How to find the length of an array
printf(" Mode two :len=%d\n", sizeof(p) / sizeof(int));
return 0;
}
Mode one :len=5
Mode two :len=1
- Mode one : Borrow the array name to find the length of the array , The evaluable array has 5 Elements , correct .
- Mode two : Using a pointer to find the length of an array , The obtained length is 1,
error . as a result of :
- p It's just a point to int Pointer to type , The compiler does not know whether it points to an integer or an array .
- sizeof(p) What you get is p The number of bytes occupied by the pointer variable itself , Instead of the number of bytes occupied by the entire array .
- For arrays a, Its type is int [6], It means that this is a possession 6 individual int A collection of data ,1 individual int The length of is 4,6 individual int The length of is 4×6 = 24,sizeof Easy to find .
- For pointer variables p, Its type is int *, stay 32 Length in bit environment 4, stay 64 Length in bit environment 8.
- in the final analysis ,a and p The types of these two symbols are different , The data referred to are also different , They are not the same thing ,sizeof The length is calculated according to the symbol type ,a and p Different types of , The length obtained is naturally different .
The compiler will create a special table during compilation , It is used to save the name and the data type corresponding to the name 、 Address 、 Scope, etc .sizeof Is an operator , It's not a function , Use sizeof The length of the corresponding symbol can be queried from this table .
Above contents , Source blog :《【C Language notes 】 Arrays are not equivalent to pointers 》
2. Similarities
1. When using indexes
| 1 | 2 | 3 |
|---|---|---|
| a[i] = p[i] | *(p+i) = *(a+i) | *p + 1 = *a + 1 |
#include <stdio.h>
int main(void)
{
int a[] = {
1, 2, 3, 4, 5 }, * p, i = 2;
p = a;
printf("p[i]---------%d \n", p[i]);
printf("a[i]---------%d \n", a[i]);
printf("\n");
printf("*(p + i)---------%d \n", *(p+i));
printf("*(a + i)---------%d \n", *(a+i));
printf("\n");
printf("*p + i---------%d \n", *p + i);
printf("*a + i---------%d \n", *a + i);
}
p[i]---------3
a[i]---------3
*(p + i)---------3
*(a + i)---------3
*p + i---------3
*a + i---------3
- Remove the subscript operator [ ] Is based on the pointer , Its function is to add a pointer to an integer , A new pointer is generated , Then from this new pointer ( New address ) Get data on ;
- The two operands of the subscript operator are interchangeable , It doesn't care about the order of the operands . If you wish to visit page 3 Elements , Then you can write a[3], You can also write 3[a]
- a[3] Equivalent to *(a + 3),3[a] Equivalent to *(3 + a), Just transpose the two operands of addition .
- When using Subscripts , The compiler will automatically adjust the subscript step size to the size of the array elements . Array a Every element in is int type , The length is 4 Bytes , that a[i+1] and a[i] The distance in memory is 4( instead of 1).
2. When an array is used as a function parameter
- Equating arrays as formal parameters with pointers is for efficiency reasons .
- An array is a collection of data of the same type , There is no limit to the number of data , Maybe only a few , There could be thousands of . If you want to pass the entire array , The overhead in both time and memory space can be very large . And in most cases , We don't really need a copy of the entire array , We just want to tell the function which particular array is of interest at that moment .
#include <stdio.h>
void func(char arr[]) {
arr[2] = 'd';
printf("arr[2]--------%c \n", arr[2]);
}
int main()
{
char arr[] = "abcd";
func(arr); // here , Pass the array name to the function , Is the pointer representing the array
}
arr[2]--------d
The above blog posts , source :《 When exactly will the array be converted to a pointer 》
边栏推荐
- 1027 colors in Mars (20 points)
- [untitled]
- N - Is There A Second Way Left? (minimum spanning tree, Kruskal)
- 1151 LCA in a binary tree (30 points)
- 文本匹配——【NAACL 2021】AugSBERT
- A. Theatre Square(codefore)
- Matlab function for limit, definite integral, first-order derivative, second-order derivative (classic examples)
- Is Domain Driven Design (DDD) reliable?
- CCF image rotation (Full Score code + problem solving idea) 201503-01
- FoxPro and I
猜你喜欢

FoxPro and I

Win10 one click Reset win10 to solve all system bugs without deleting any files and Applications

Infrastructure is code. What are you talking about?

Single cycle CPU of the design group of West University of Technology

Preliminary study on AI noise reduction evaluation system of sound network

Technology sharing | anyrtc service single port design

Is Domain Driven Design (DDD) reliable?

Voice codec based on machine learning Agora silver: support high quality voice interaction at ultra-low bit rate

Three types of technical debt that programmers often encounter: code, data, and architecture

The sound network has fully opened the real-time transmission network sd-rtn, which has been free of network wide accidents for seven years - this is FPA!
随机推荐
这种零件该怎么编程加工?
Machine learning feature selection
Quick sort (C language)
M - smooth engineering continuation (minimum spanning tree)
Zero basic C language learning notes -- first introduction -- 2 data types & variables and constants
DR-TANet: Dynamic Receptive Temporal Attention Network for Street Scene Change Detection
CCF call auction (full mark code + problem solving ideas + skill summary) 201412 - 3
NPM install --global --save --save dev differences
1131: genetic correlation
G - building a space station
B. Moamen and k-subarrays (codeforce+ binary search)
Abstract meaning
1019 general palindromic number (20 points)
Database connection to company database denied
CCF image rotation (Full Score code + problem solving idea) 201503-01
1062 talent and virtue (25 points)
Explain service idempotency design in detail
001 data type [basic]
1150 traveling salesman problem (25 points)
One dimensional and two dimensional array addresses