Passing two-dimensional arrays as function parameters in C language

In c language, it is often necessary to pass two-dimensional arrays through functions. There are three ways to achieve this, as follows:

Method 1, the  formal parameter gives the length of the second dimension.

E.g:

#include <stdio.h>
void func(int n, char  str[ ][5] )
{
 int i;
 for(i = 0; i < n; i++)
  printf("/nstr[%d] = %s/n", i, str[i]);
}

void main()
{
 char* p[3];
 char str[][5] = {"abc","def","ghi"};
 func(3, str);
}

Method two, the formal parameter is declared as a pointer to an array.

E.g:

#include <stdio.h>
void func(int n, char  (*str)[5] )
{
 int i;
 for(i = 0; i < n; i++)
  printf("/nstr[%d] = %s/n", i, str[i]);
}

void main()
{
 char* p[3];
 char str[][5] = {"abc","def","ghi"};
 func(3, str);
}

 Method three, the formal parameter is declared as a pointer to a pointer.

E.g:

#include <stdio.h>
void func(int n, char **str)
{
 int i;
 for(i = 0; i < n; i++)
  printf("/nstr[%d] = %s/n", i, str[i]);
}
void main()
{
 char* p[3];
 char str[][5] = {"abc","def","ghi"};
 p[0] = &str[0][0];
 p[1] = str[1];
 p[2] = str[2];
    func(3, p);

}



In addition, the description of the third parameter passing method : when using the two-dimensional array (pointer) passed in the parameter to obtain the value of the array, the form (array[i][j]) cannot be used to obtain the value. The two-dimensional array should be regarded as a one-dimensional array, and the form of array[i * j + j] should be used to obtain the value.

Personal understanding: This is because when passing parameters, we pass the array[][] array as a secondary pointer, so I think he degenerates the attributes of the array into the attributes of the secondary pointer, so there is no way here. Use array[i][j] to get array values. The output format is as follows

int tag = 0;//tag tag, the tag required when outputting a two-dimensional array in the method
printf("Use the passed 2D array parameter to output a 2D array\n");
	for(i = 0; i < rows*columns; i++) {	
		printf("%d,", array[i]);
		if(tag == columns-1) {
			tag = 0;
			printf("\n");
		} else {
			tag++;
		}
	}

 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325721392&siteId=291194637