1. Several knowledge points
- The four areas of memory: stack, global (static), and constant area. The remaining space can not be used at will for the time being; the remaining space can be used as long as it is applied for through the malloc function;
- To apply for a single
int
variable on the heap :int* p = (int*)malloc(sizeof(int));
int
Method to apply for an array on the heap :int* p = (int*)malloc(sizeof(int)*5);
- The address on the heap can be used across functions, and is released by the free function when it is not needed;
Second, the secondary pointer
Problem introduction
char* ss[4] = { "basic","fortran","C++" };//每个元素都是char*类型
For such an array of pointers, what kind of pointers should be used to traverse? The answer is: secondary pointer
char** p = ss; // 二级指针变量p,指向一个指针数组
Example 1-Define pointer arrays in the stack and on the heap respectively
char* ss[] = {
"abc","dd","aaa",NULL };
char* *p = (char**)malloc(sizeof(char*) * 4);
int i = 0;
while (i < 4)
{
p[i] = ss[i];
++i;
}
free(p);
Example 2-Level 2 pointer traverses pointer array
#include <stdio.h>
void main()
{
char* p = "Test";
char* ar[4] = {
"basic","fortran","C++" }; // 一共4个元素,每个元素都是char*类型
printf("sizeof(ar)=%d\n", sizeof(ar));
char* *pp = ar;
int i = 0;
while (i < sizeof(ar) / sizeof(ar[0]))
{
p = pp[i];
printf("第%d个指针变量指向的内容是:%s\n", i, p); //pp[i]的类型是char*
++i;
}
printf("p指向的地址是:0x%p内存空间上的内容是:%s\n", p, p);
}
operation result
Example 3
#include<stdio.h>
void main()
{
int ar[10] = {
33,55 };
int n = 10;
int* p = &n; //一级指针变量指向了一个普通变量,为了远程操控普通变量存储的数据
int* q = ar;
*p = -1;
//int* *pp = &p; //指针变量的指针是二级指针
//pp = &q;
//*pp = p;//*p或p[0]远程操控一个一级指针变量,让它指向到其他地址
int* as[10] = {
ar,&n,NULL }; // 每个元素都是一个一级指针变量
int* *pp = as; // =&as[0]; // as[0]类型是int*类型
int i = 0;
while (i < sizeof(as) / sizeof(as[0]))
{
printf("第%d条指针指向:0x%p\n", i, pp[i]); //pp[i]类型是int*类型
++i;
}
printf("\n");
int ar1[] = {
32,56,93,56,-1,0 }; //每个元素都是int类型
int* p1 = &ar1[0]; // ar; // 一级指针变量p, 指向一个普通变量的一维数组
while (*p1)
{
printf("p[%d]=%d\n", p1 - ar1, *p1);
//指针的减法: 相差字节/sizeof(int),逻辑上是几个int
++p1;
}
}