当前位置:网站首页>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 》
边栏推荐
- DR-TANet: Dynamic Receptive Temporal Attention Network for Street Scene Change Detection
- (Niuke) BFS
- Summary of system stability construction practice
- Matlab two-dimensional array example (extract data)
- FoxPro and I
- 立式加工中心调试的步骤
- 1150 traveling salesman problem (25 points)
- Rte2021 review of the practice and the way of AI OPS landing
- One dimensional and two dimensional array addresses
- B. Moamen and k-subarrays (codeforce+ binary search)
猜你喜欢

Scattered knowledge of C language (unfinished)

How to get palindrome number in MATLAB (using fliplr function)

FoxPro and I

Summary of system stability construction practice

Repair of incorrect deletion of win10 boot entry

Anyrtc implements application scenarios based on webrtc

Xiao Sha's pain (thinking problem)

The principle of fluent 2 rendering and how to realize video rendering

Webrtc: industrial application based on Internet of things

CCF call auction (full mark code + problem solving ideas + skill summary) 201412 - 3
随机推荐
文本匹配——【NAACL 2021】AugSBERT
Basic literacy - four common software architectures
CCF elimination games (Full Score code + problem solving ideas + skill summary) February 2, 2015
1137: encrypted medical record
B. Moamen and k-subarrays (codeforce+ binary search)
Four solutions to cross domain problems
Zero basic C language learning notes -- first introduction -- 2 data types & variables and constants
Matlab to find prime pairs within 100
Quick sort (C language)
1031 Hello world for u (20 points)
左旋梯形螺纹的编程
Developer practice - the future of Agora home AI audio and video
How to program and process such parts?
这种零件该怎么编程加工?
1150 traveling salesman problem (25 points)
CCF date calculation (Full Score code + skill summary) February 2, 2015
(Niuke) BFS
Matlab finds a prime number that is greater than a given integer and follows this integer
Anyrtc implements application scenarios based on webrtc
1132: stone scissors cloth