About two-dimensional array passing parameters as form parameters (convert)

Source: Internet
Author: User
Tags sorts

The storage method of a two-dimensional array is no different from that of a one-dimensional array. But how can I write the parameters of a two-dimensional array? Note that the form parameter in the function is actually equivalent to a declaration without generating memory allocation. The purpose of the form parameter is to let the compiler know the Data Type of the function parameter.

Correct: void func (INT array [3] [10]); void func (INT array [] [10]); can omit the size of the first dimension

The error is void func (INT array [] []. this method can only be used during initialization); this is also an error: void func (const int M, const int N, int array [m] [N]); or void func (int m, int N, int array [m] [N]); we all know that the index of an array must be a constant expression, void func (const int m, const int N, int array [m] [N]); If const int m is not initialized, the system will automatically initialize m or N to 0, so this is wrong

If we use the void func (INT ** array, int M, int N) format like this, then in the actual function call, we need to perform a forced conversion before we can use it, we can call void func (INT **) array, int M, int N) in this way. When calling a function, we need to write the array form as a pointer, for example, * (int *) array + N * I + J); writing int array [I] [J] directly leads to errors. Compilation is successful, and execution in the VC compiler is abnormal, the Dev compiler generates a random value because the compiler cannot properly address int array [I] [J]. Of course, the processing results of various compilers are different. If our form parameters are arrays, we can use pointers or arrays in the function body. However, if we use pointers in form parameters, we 'd better use pointers, sometimes an error occurs in the form of arrays. This is true for two-dimensional arrays.

 

========================================================== ========================================================== ======================================

 

The following is an excerpt from the Internet:
First, I cited the original article in the section C programming prepared by Mr. Tan haoqiang. It briefly introduces how to pass two-dimensional arrays as parameters. The original Article is as follows (slightly changed, forgive me ):

[Start with the original article]
The two-dimensional array name can be used as the real parameter or form parameter. when defining the form parameter array in the called function, you can specify the size of all dimensions or omit the size description of the first dimension. For example:
Void func (INT array [3] [10]);
Void func (INT array [] [10]);

Both of them are valid and equivalent, but the two-dimensional or higher-dimensional sizes cannot be omitted. the following definition is invalid:
Void func (INT array [] []);
Because the starting address of the array is passed from the real parameter, it is stored in the memory according to the array arrangement rules (stored by row), without the partition and column. If the column number is not specified in the form parameter, the system cannot determine how many rows and columns should be. It cannot specify only one dimension rather than the second dimension. The following statement is incorrect:
Void func (INT array [3] []);

The dimension of the real parameter array can be greater than that of the form parameter array. For example, the real parameter array (zhihui3409 Note: it should be a form parameter) is defined:
Void func (INT array [3] [10]);
The array of parameters (zhihui3409 Note: it should be real parameters) is defined:
Int array [5] [10];
At this time, the form parameter array only takes part of the real parameter array, and the rest does not work.
[End of original article]

As you can see, when using a two-dimensional array as a parameter, you must specify the size of all dimensions or omit the first dimension, but do not omit the size of the second or higher dimensions, this is restricted by Compiler Principles.
According to the compilation principle, if we omit the size of the second or higher dimension, the compiler will not know how to address it correctly. However, when writing a program, we need to use a two-dimensional array with non-fixed dimensions as a parameter. This is hard to solve and the compiler cannot recognize it. What should we do? Don't worry. Although the compiler cannot recognize it, we can treat it as a two-dimensional array instead of a normal pointer, and add two parameters to specify the dimensions, then we manually address the two-dimensional array, so that we can pass the two-dimensional array as a function parameter. Based on this idea, we can change the fixed-dimension parameter to a random-dimension parameter, for example:
Void func (INT array [3] [10]);
Void func (INT array [] [10]);
Changed:
Void func (INT ** array, int rowsize, int linesize );
In the transformed function, the formula "array [I] [J]" is incorrect (you can try it if you don't believe it), because the compiler cannot properly address it, therefore, we need to simulate the compiler behavior to manually convert array [I] [J]:
* (Int *) array + linesize * I + J); processing a two-dimensional array as a one-dimensional array is easier to understand. For other methods, see the second point in the summary below.

Summary of array as a form parameter:
1. One-dimensional array as function parameters
When an array is used as a form parameter, the compiler usually only checks the real parameters associated with the array form parameters. The checked items include whether the real parameters are pointers, pointer types, and array element types, however, the length of the array is not checked.
Void print (int * A [])
Void print (int * A [10])
Void print (int *)
Both of the above are level-2 pointers, and the following is level-1 pointers.

In many cases, defining an array parameter as a pointer is much easier than defining an array syntax. After being defined as a pointer, the function can operate array elements conveniently with the help of pointers.
When an array is passed as a non-reference type, the array is automatically converted to a pointer of the same type, that is, a copy of the corresponding type of arguments is initialized. When a function is called, the actual operation of the function is a copy of the pointer, instead of modifying the value of the real parameter pointer, but the value of the array element can be changed through the pointer.

2. Multi-dimensional array Transfer
The element of a multi-dimensional array is an array.

Two-dimensional arrays can be treated as one-dimensional or two-dimensional arrays. The following two examples use these two methods. The 3rd examples are a little different, but they actually use a one-dimensional array for intermediate transition processing.

// Example 1 treats a two-dimensional array as a one-dimensional array: // print_array achieves the same effect as the Circular printf in the main function # include <stdio. h> void print_array (int * P, int rowsize, int linesize) {int I, j; for (I = 0; I <rowsize; I ++) {for (j = 0; j <linesize; j ++) printf ("% d", * (p + I * linesize + j )); printf ("\ n") ;}} void main () {int I, j, a [3] [3] ={{, 0, 0 },{ 0, 0, 1 }}; print_array (int *) A, 3, 3); for (I = 0; I <3; I ++) {for (j = 0; j <3; j ++) printf ("% d", * (a + I) + j )); printf ("\ n ");}}

 


Example 2 process the two-dimensional array as a two-dimensional array
The following is a parameter passing program for the string array, which sorts the strings in the string array in ascending order:
// Wordsort sorts five strings
# Include "stdio. H"
# Include "stdlib. H"
# Include "string. H"
Void wordsort (char P [] [10], int rowsize)
{
Int n = 0, M;
Char temp [10];
For (n = 0; n <rowsize; n ++)
For (M = n + 1; m <rowsize; m ++)
If (strcmp (P [m], p [N]) <0)
{
Strcpy (temp, P [N]);
Strcpy (P [N], p [m]);
Strcpy (P [m], temp );
}
For (n = 0; n <5; ++ N)
Printf ("in subfunction: % s \ n", P [N]);
}

Void main ()
{
Int K = 0;
Char word [5] [10];
For (; k <5; ++ K)
Scanf ("% s", & word [k]);
Wordsort (word, 5 );
Printf ("sorted word: \ n ");
For (k = 0; k <5; k ++)
Printf ("in main function: % s \ n", word [k]);
System ("pause ");
}
  
Example 3 passing parameters with "Row Pointer"
Run the following program:
/************************************/
// The two-dimensional array is used as one of the parameter passing methods of the form parameter.
/************************************/
# Include <stdio. h>
Void print_array_1 (INT (* A) [3], int row_size)
{
Int J;
For (j = 0; j <3 * row_size; j ++)
{
Printf ("% d", (* A) [J]);
If (J % 3 = 2) printf ("\ n ");
}
}

Void print_array_2 (INT (* A) [3], int row_size)
{
Int I, J;
For (I = 0; I <row_size; I ++)
{
For (j = 0; j <3; j ++)
Printf ("% d", * (a + I) + j ));
Printf ("\ n ");
}
}

Void main ()
{
Int I, j, value = 0;
Int A [4] [3] = {0 };
For (I = 0; I <4; I ++)
For (j = 0; j <3; j ++)
A [I] [J] = value ++;

Print_array_1 (A, 4 );
Printf ("\ n ");
Print_array_2 (A, 4 );
}


The two functions in this program implement the same function: Print array elements. This method may be confusing: What is int (* A) [3? I have to read the strong brother's book (P229-P230), the above writes (in this example ):
* A has three elements, each of which is an integer. That is, the object that a points to is an array with three integer elements, that is, a is a row pointer.
 
Emphasize the role of INT (* A) [3] brackets again. If you do not understand the importance of INT (* A), carefully compare the yellow background code in this article.
  
In addition, it is more convenient to use this method to process string arrays (2D arrays of struct type): use this example to end this article:

// Print the strings in the array (one line)
# Include <stdio. h>
Void print_string (char (* string) [20], int row_size)
{
Int I;
For (I = 0; I <row_size; I ++)
Printf ("% s \ n", string + I );
}

Void main ()
{
Char A [6] [20] = {"God", "Bless", "you", "who", "help", "themselves "};
Print_string (A, 6 );
}

About two-dimensional array passing parameters as form parameters (convert)

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.