Reprinted: https://blog.csdn.net/qq_41822235/article/details/81142107
table of Contents
One, use a secondary pointer to achieve
Second, use the array pointer to achieve
Three, use a one-dimensional array to simulate a two-dimensional array
One, use a secondary pointer to achieve
Idea: The use of secondary pointers is similar to the use of two-dimensional array names
#include<stdio.h>
#include<malloc.h>
int main()
{
//5行2列的数组
int **p = (int **)malloc(sizeof(int *) * 5);
for (int i = 0; i < 5; ++i)
{
p[i] = (int *)malloc(sizeof(int) * 2);
}
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 2; ++j)
{
//输出数组每个元素地址
printf("%p\n", &p[i][j]);
}
}
for (int i = 0; i < 5; ++i)
free(p[i]);
free(p);
return 0;
}
Features:
- The element addresses in the same row are continuous, and the element addresses in different rows are not necessarily continuous.
- The process of freeing up the requested space also requires attention.
Second, use the array pointer to achieve
Array pointer and pointer array are different. The array pointer is a pointer variable, and its essence is still a variable. The essence of a pointer array is an array, and the stored element type is a pointer type.
Even if you know the difference between them well, after a long time, it is still easy to confuse the definition. The precedence of operators is also very important. ()> []> *. Keep it in mind.
#include<stdio.h>
#include<malloc.h>
int main()
{
//申请一个5行2列的整型数组
int(*p)[2] = (int(*)[2])malloc(sizeof(int) * 5 * 2);
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 2; ++j)
{
//输出数组每个元素地址
printf("%p\n", &p[i][j]);
}
}
free(p);
return 0;
}
Features:
- The applied address space is always continuous.
- The method of freeing up application space is worthy of comparison.
Three, use a one-dimensional array to simulate a two-dimensional array
#include<stdio.h>
#include<malloc.h>
int main()
{
int *p = (int *)malloc(sizeof(int) * 5 * 2);
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 2; ++j)
{
//输出数组每个元素地址
printf("%p\n", &p[i*2+j]);
}
}
return 0;
}
Features:
- The addresses applied for are consecutive.
- The way to release the requested space is worth noting.