Wonderful example 3 of C language: Please write the function fun. The function of the function is to put the data in the two-dimensional array with M rows and N columns into the one-dimensional array in order of columns.

1. Question

Please write the function fun. The function of the function is: put the data in the two-dimensional array with M rows and N columns into the one-dimensional array in order of columns.

For example, the data in a two-dimensional array is:

    33  33  33  33

    44  44  44  44

    55  55  55  55

Then the contents of the one-dimensional array should be:

    33  44  55  33  44  55  33  44  55  33  44  55

2. Program analysis

Problem-solving ideas: The reference program provided in this question uses two layers of for loops, inner and outer loops, to store the data from rows 1 to 3 to the corresponding positions in the array in column order, and at the same time uses the formal parameter variable n to count a The number of data stored in the dimensional array, which implements placing the data in the two-dimensional array with M rows and N columns into the one-dimensional array in row order.

3. Program source code

#include <stdio.h>
void fun(int s[][10], int b[], int *p, int m, int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            *b++ = s[j][i];
        }
    }
}
int main(int argc, char const *argv[])
{
    //int a[3][10];
    int b[30];
	int a[3][10]={
   
   {33,33,33},{44,44,44},{55,55,55}};
    fun(a, b, b, 3, 4);
    for (int i = 0; i < 3 * 3; i++)
    {
        printf("%d",b[i]);
    }
}

4. Input and output

Standard output:

 33  44  55  33  44  55  33  44  55  33  44  55

 

 

Guess you like

Origin blog.csdn.net/T19900/article/details/129509163