C USES the malloc function to apply an example of a two dimensional dynamic array

  • 2020-06-01 10:26:12
  • OfStack

C USES the malloc function to apply an example of a 2 - dimensional dynamic array

C language in the program running dynamic application and release of memory 10 minutes convenient, 1 - dimensional array application and release relatively simple.

Sample one

#include <stdio.h> 
int main() 
  char * p=(char *)malloc(sizeof(char)*5);// Applications include 5 An array of characters  
  return 0; 

Is it so easy to apply for 2-d dynamic memory? The answer is no. There are several ways to apply a 2 - dimensional array

Sample two

/*  To apply for 1 a 5 line 3 A character array of columns */ 
char **p=NULL;int i; 
p=(char ** )malloc(sizeof(char *)*5); 
  p[i]=malloc(sizeof(char)*3) ;  

The advantage of this approach is that both the rows and columns are mutable, but you must release them multiple times. Release p[n] first, then p

/* Free memory */ 

Sample three

/* Use a pointer to an array to request memory */ 
char (*p)[3]=(char(*)[3])malloc(sizeof(char)*5*3)//p is 1 Individual point includes 3 Pointer to an array of elements  

The memory allocated in this way only needs to be freed once


The disadvantage of this approach is that columns are immutable!

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!

Related articles: