Three methods of passing two dimensional arrays as function arguments in C language

  • 2020-06-19 11:19:37
  • OfStack

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

In method 1, the formal parameter gives the length of the second dimension.

Such as:


#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 2, the parameter is declared as a pointer to the array.

Such as:


#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 3, where the parameter is declared as a pointer to a pointer.

Such as:


#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 third way of parameter passing instruction: when using the 2-dimensional array (pointer) passed by the parameter in the function to carry out the array value, cannot use ( array[i][j] ) to evaluate in this form. Think of a 2-dimensional array as a 1-dimensional array array[i * j + j] I'm going to evaluate it in this form.

Personal understanding: This is because at the time of transmission, we will array[][] Arrays are passed as level 2 Pointers, so I think it degrades the array properties to level 2 Pointers, so it can't be used here array[i][j] This is the way to evaluate an array. Output format is as follows


int tag = 0;//tag Tag, output in the method 2 The tag required for dimensional arrays 
printf(" Use the ones that are passed in 2 Dimensional array parameter output 2 Dimensional array \n");
 for(i = 0; i < rows*columns; i++) { 
  printf("%d,", array[i]);
  if(tag == columns-1) {
   tag = 0;
   printf("\n");
  } else {
   tag++;
  }
 }

conclusion


Related articles: