Article Directory
foreword
This article will introduce pointer arrays and array pointers to understand the difference between the two. Learn the difference between array name, & array name (take address array name). Master character pointers, function pointers, and other related content.
1. Distinguish between pointer array and array pointer
Let's look at an example first:
//定义如下两个变量
int *p1[10];
int (*p2)[10];
How to distinguish whether p1 and p2 are pointer arrays or array pointers ?
Before that, let's understand the corresponding concepts of the two.
(1) Pointer array: Simply speaking, a pointer array is an array that stores pointers .
(2) Array pointer : A pointer that can point to an array .
Note: The meaning of the two can be distinguished by the last two words .
Analyze the above example:
int *p1[10]; //指针数组
int (*p2)[10]; //数组指针
Note: The priority of [ ] is higher than that of * , so p1 will be combined with [ ] first to form an array, and the elements stored in the array are pointers.
2. Distinguish between array name and & array name
Define the following arrays:
int a[10];
a: The name of the array, indicating the address of the first element of the array.
If the address of the array name a is taken, namely: &a , what does &a mean?
Here is an example to illustrate this problem:
#include <stdio.h>
int main()
{
int a[10] = {
0 };
printf("%p\n", a);
printf("%p\n", &a);
printf("===================\n");
printf("%p\n", a + 1); //a+1
printf("%p\n", &a + 1); //&a+1
return 0;
}
The results are analyzed as follows:
Summary: &a represents the address of the array , not the address of the first element of the array.
&a+1 represents the address of the entire array +1 , skipping the size of the entire array.
3. Character pointer
Common character pointers: char * p;
(1) Use method 1:
#include <stdio.h>
int main()
{
char c = 'A';
char *p = &c;
printf("%c\n", *p);
return 0;
}
Result:
(2) Use method 2:
#include <stdio.h>
int main()
{
char* p = "hello";
printf("%s\n", p);
return 0;
}
Results Analysis:
Note the following example:
#include <stdio.h>
int main()
{
char s1[] = "hahahaha!";
char s2[] = "hahahaha!";
char *s3 = "hahahaha!";
char *s4 = "hahahaha!";
if(s1 ==s2)
printf("s1 = s2\n");
else
printf("s1 != s2\n");
if(s3 ==s4)
printf("s3 = s4\n");
else
printf("s3 != s4\n");
return 0;
}
Result analysis:
4. Function pointer
Function pointer: A pointer used to store the address of a function.
For example:
#include <stdio.h>
void print()
{
printf("hello\n");
}
int main()
{
printf("%p\n", print);
printf("%p\n", &print);
return 0;
}
If you want to save the function address in the above example with a pointer, you need to use a function pointer.
Right now:void (*print)();
Common function pointers are:
int(*fun1)(int,int);
void(*fun2)(int);
char(*fun3)();
Summarize
That's all for this article.