How to operate a two-dimensional array with level two pointers in C language

Source: Internet
Author: User

Accessing a two-dimensional array through a level two pointer requires assigning a one-dimensional array pointer equal to the number of rows in a two-dimensional array, and then assigning each header of a two-dimensional array to a one-dimensional pointer in the corresponding position. It can then be accessed directly by a two-dimensional pointer.

Refer to the code below, you can see the specific annotation auxiliary understanding.

12345678910111213141516171819202122232425 #include <stdio.h>//输入输出头文件。#include <stdlib.h>//本程序需要用到malloc/free函数,引用该头文件。intmain(){    int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12}; //定义二维数组a,并赋值从1-12.    int** p = NULL;//定义二维指针。    inti, j;        p = (int**)malloc(sizeof(int*) *3);//要访问的数组有三行,所以申请三个一维指针变量。    for(i = 0; i < 3; i ++)    {        p[i] = a[i];//将二维数组行地址赋值到对应的一维指针上。    }        for(i = 0; i < 3; i ++)    {        for(j = 0; j < 4; j ++)            printf("%d ", p[i][j]); //用指针输出元素。p[i][j]这里也可以写作*(*(p+i) + j)。        printf("\n"); //每行输出后加一个换行    }        free(p);//释放申请的内存。        return0;}

Using two-dimensional pointers to access two-dimensional arrays is used for function calls.

For a one-dimensional array, if the function parameter is a one-dimensional pointer, the array name can be used directly as a function parameter. However, if the function parameter is a two-dimensional pointer, the direct use of two-dimensional array names to make the parameter access error occurs because the two-dimensional pointers and two-dimensional arrays are accessed differently, you need to do the conversion in the sample code.

Another common method is to use the memory continuity of a two-dimensional array to convert a two-dimensional array to a one-dimensional array, regardless of the subject matter, without any further description.

Https://zhidao.baidu.com/question/585729445.html

How to operate a two-dimensional array with level two pointers in C language

Related Article

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.