Request and return two-dimensional space on heap space

Source: Internet
Author: User

Two-dimensional and two-dimensional arrays have two-dimensional logic, but the two-dimensional array is continuous, two-dimensional space is not necessarily continuous, we can apply for a continuous two-dimensional space, you can also apply for discontinuous two-dimensional space, the following to introduce two applications and return to a two-dimensional space method:

Apply and return a contiguous two-dimensional space, this is to use a pointer array to manage the continuous two-dimensional space.

1#include <stdio.h>2#include <stdlib.h>3 intMainvoid)4 {5     int(*p) [5]=(int(*) [5])malloc(sizeof(int)*3*5);6     intI=0, j=0;7      for(i=0;i<3; i++)8          for(j=0;j<5; j + +)9         {Tenp[i][j]=i*J; One         } A      for(i=0;i<3; i++) -          for(j=0;j<5; j + +) -         { theprintf"%d\t", P[i][j]); -         } -     return 0; -}

Applying and returning a discontinuous two-dimensional space, the principle is to first use a level two pointer to a space. , all of them are first-level pointers, and then each of these level pointers points to a one-dimensional space, so that the two-level pointer to or manages the two-dimensional space.

1#include <stdio.h>2#include <stdlib.h>3 int**allocmem (int Base,intRowintLine )4 {5     int**p= (int**)calloc(sizeof(int*), row);6     intI=0;7      for(i=0; i<row;i++)8     {9P[i]= (int*)calloc(Line,Base);Ten     } One     returnp; A } - intMainvoid) - { the     int Base=sizeof(int); -     introw=3, line=5; -     int**p=allocmem (Base, row,line); -     intI=0, j=0; +     intk=0; -      for(i=0; i<row;i++) +          for(j=0; j<line;j++) A         { atp[i][j]=k++; -         } -      for(i=0; i<row;i++) -          for(j=0; j<line;j++) -         { -printf"%d\t", P[i][j]); in         } -     return 0; to}

Request and return two-dimensional space on heap space

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.