Dynamically apply for a two-dimensional array

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:

  1. The element addresses in the same row are continuous, and the element addresses in different rows are not necessarily continuous. 
  2. 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:

  1. The applied address space is always continuous.
  2. 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:

  1.  The addresses applied for are consecutive.
  2. The way to release the requested space is worth noting.

Guess you like

Origin blog.csdn.net/modi000/article/details/113852864
Recommended