3维数组,行和列大小不同。

huangapple go评论71阅读模式
英文:

3-d array with different size of row and column

问题

我正在创建一个三维数组,我面临的问题是我想创建多个三维数组,但每个数组的行和列大小都不同,所以第一个矩阵的大小可以是0-2-2,而下一个矩阵可以是1-1-3,依此类推。

请不要建议创建一个大矩阵,该矩阵可以包含所有行和列的值。

我个人尝试使用结构来编写代码,我在结构中定义了2维数组(用于行和列),然后将其存储在变量e[1].array(2-d)中,我使用for循环不断根据用户输入更改数组中的行和列的值,我面临的问题是每次for循环将值更改为下一个值时,代码会覆盖自身,因此无法调用数组的先前值,因此如果对于第一个矩阵的行和列大小为2-2,然后对于第二个循环,e[1].x[1][3]数组的维度已被重新定义,因此无法调用x[2][2]。

请建议我如何存储具有不同行和列大小的三维数组,以用于每个矩阵。

int main()
{
    int matrix;
    printf("输入矩阵的数量\n");
    scanf("%d", &matrix);
    
    for (int m = 0; m < matrix; m++) {
        int row, column;
        printf("输入第 %d 个矩阵的行数\n", m + 1);
        scanf("%d", &row);
        printf("输入第 %d 个矩阵的列数\n", m + 1);
        scanf("%d", &column);

        int f[row][column];

        printf("输入所有元素从左到右\n");
        int g = 1;
        for (int j = 0; j < row; j++) {
            for (int u = 0; u < column; u++) {
                printf("%d)\n", g);
                scanf("%d", &f[j][u]);
                g = g + 1;
            }
        }

        printf("矩阵如下:\n");
        for (int s = 0; s < row; s++) {
            printf("|");
            for (int l = 0; l < column; l++) {
                printf("%d", f
展开收缩
[l]);
if (l < column - 1) { printf(" "); } } printf("|\n"); } printf("%d\n", f[0][0]); } return 0; }

期望输出:

输入矩阵的数量
2
输入第 1 个矩阵的行数
2
输入第 1 个矩阵的列数
2
输入所有元素从左到右
1)
1
2)
2
3)
3      4
4)
4
|1  2|
|3  4|
1
输入第 2 个矩阵的行数
1
输入第 2 个矩阵的列数
3
输入所有元素从左到右
1)
5
2)
6
3)
7
|5  6  7|
1

请注意,我在代码中进行了一些更改,以便在每次迭代中创建不同大小的二维数组。

英文:

i am making a three-d array the problem i am facing is i want to create multiple 3-d array however with varying size of row and column so the first matrix size could be 0-2-2 while next matrix could be say 1-1-3 so on..

kindly do not suggest making a large matrix that could have value of all the row and columns.

i personally have tried using structure to create the code, i have defined 2-d array( for row and column) in the structure and then stored it in variable e[1].array(2-d), i have used for loop to continuously change value of row and column in array based on user input, the problem i am facing is every time the for loop changes value to next the code over writes itself hence previous values of array can not be called so if for first matrix the size of row and column was 2-2 and next is 1-3 so e[1].x[2][2] have some value then for second loops e[1].x[1][3] the dimensions of x have been re-defined hence i could not call x[2][2].
kindly suggest ways i could store 3-d array with different size of row and column for each matrix.

 int main()
 {
 int matrix;
 printf(&quot;ENTER NUMBER OF MATRICES\n&quot;);
 scanf(&quot;%d`&quot;, &amp;matrix);
 int row, column;


for (int m = 0; m &lt; matrix; m++) {
    printf(&quot;ENTER NUMBER OF ROWS IN %d MATRICE\n&quot;, m + 1);
    scanf(&quot;%d&quot;, &amp;row);
    printf(&quot;ENTER NUMBER OF column IN %d MATICE\n&quot;, m + 1);
    scanf(&quot;%d&quot;, &amp;column);
     struct x {
  int f[row][column];
};
    struct x k[m];
    int g = 1;

    printf(&quot;ENTER ALL ELEMENT LEFT TO RIGHT\n&quot;);
    for (int j = 0; j &lt; row; j++) {
        
        for (int u = 0; u &lt; column; u++) {
            
            printf(&quot;%d)\n&quot;, g);
            scanf(&quot;%d&quot;, &amp;k[m].f[j][u]);
            g = g + 1;
        }
    }
    for (int s = 0; s &lt; row; s++) {
        printf(&quot;|&quot;);
        for (int l = 0; l &lt; column; l++) {
             
            printf(&quot;%d&quot;, k[m].f
展开收缩
[l]); if (l &lt; column - 1) { printf(&quot; &quot;); } } printf(&quot;|\n&quot;); } printf(&quot;%d&quot;, k[0].f[0][0]); // error here calling over written value } return 0;

expectation:

 ENTER NUMBER OF MATRICES
 2
 ENTER NUMBER OF ROWS IN 1 MATRICE
 2
 ENTER NUMBER OF column IN 1 MATICE
 2
 ENTER ALL ELEMENT LEFT TO RIGHT  
 1)
 1
 2)
 2
 3)
 3      4
 4)
 4
 |1  2|
 |3  4|
 ENTER NUMBER OF ROWS IN 2 MATRICE
 1
 ENTER NUMBER OF column IN 2 MATICE
 3
 ENTER ALL ELEMENT LEFT TO RIGHT
 1)
 5
 2)
 6
 3)
 7
 |5  6  7|
 1 // error here in output

答案1

得分: 4

由于每个矩阵可能具有不同的大小,您应该分别管理每个矩阵并分别记录其尺寸。下面的代码显示了如何使用结构类型来实现这一点。

通常的C语言实现支持可变长度数组,因此您可以使用它来更简单地访问矩阵元素。下面的程序演示了如何使用指向可变长度数组的指针来指向矩阵的行。内存地址使用void *记录在结构体中,因为我们不能在结构体中使用可变修改的类型,但在需要时会声明一个单独的变量,并将其设置为矩阵的内存起始地址。

在没有使用可变长度数组的情况下,您将不得不使用手动算术计算来访问线性数组中的元素。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    // 读取矩阵的数量。
    int NMatrices;
    printf("输入矩阵的数量:");
    if (1 != scanf("%d", &NMatrices))
    {
        fprintf(stderr, "错误,无法读取矩阵数量。\n");
        exit(EXIT_FAILURE);
    }
    if (NMatrices < 0)
    {
        fprintf(stderr, "错误,矩阵数量为负数。\n");
        exit(EXIT_FAILURE);
    }

    // 定义用于管理矩阵的类型。
    struct MatrixInformation
    {
        void *Memory;        // 用于存储矩阵的内存。
        int NRows, NColumns; // 行数和列数。
    };

    // 分配内存以管理NMatrices个矩阵。
    struct MatrixInformation *Matrices = malloc(NMatrices * sizeof *Matrices);
    if (!Matrices)
    {
        fprintf(stderr, "错误,无法分配内存。\n");
        exit(EXIT_FAILURE);
    }

    // 读取每个矩阵。
    for (int m = 0; m < NMatrices; ++m)
    {
        // 读取此矩阵的行数和列数。
        int NRows, NColumns;
        printf("输入第 %d 个矩阵的行数:", m + 1);
        if (1 != scanf("%d", &NRows))
        {
            fprintf(stderr, "错误,无法读取行数。\n");
            exit(EXIT_FAILURE);
        }
        if (NRows <= 0)
        {
            fprintf(stderr, "错误,行数不是正数。\n");
            exit(EXIT_FAILURE);
        }
        printf("输入第 %d 个矩阵的列数:", m + 1);
        if (1 != scanf("%d", &NColumns))
        {
            fprintf(stderr, "错误,无法读取列数。\n");
            exit(EXIT_FAILURE);
        }
        if (NColumns <= 0)
        {
            fprintf(stderr, "错误,列数不是正数。\n");
            exit(EXIT_FAILURE);
        }

        // 为矩阵创建临时指针并分配内存。
        int (*Matrix)[NColumns] = malloc(NRows * sizeof *Matrix);
        if (!Matrix)
        {
            fprintf(stderr, "错误,无法分配内存。\n");
            exit(EXIT_FAILURE);
        }

        // 保存行数、列数和内存地址。
        Matrices[m].NRows = NRows;
        Matrices[m].NColumns = NColumns;
        Matrices[m].Memory = Matrix;

        // 获取矩阵元素的值。
        for (int r = 0; r < NRows; ++r)
            for (int c = 0; c < NColumns; ++c)
            {
                printf("输入元素 [%d, %d] 的值:", r + 1, c + 1);
                if (1 != scanf("%d", &Matrix[r][c]))
                {
                    fprintf(stderr, "错误,无法读取元素。\n");
                    exit(EXIT_FAILURE);
                }
            }
    }

    // 打印每个矩阵。
    for (int m = 0; m < NMatrices; ++m)
    {
        printf("矩阵 %d:\n", m + 1);

        // 获取行数、列数和内存地址。
        int NRows = Matrices[m].NRows;
        int NColumns = Matrices[m].NColumns;
        int (*Matrix)[NColumns] = Matrices[m].Memory;

        // 打印每一行。
        for (int r = 0; r < NRows; ++r)
        {
            // 每行以分隔符开始,没有空格。
            printf("|%d", Matrix[r][0]);

            // 用两个空格分隔每个元素。
            for (int c = 1; c < NColumns; ++c)
                printf("  %d", Matrix[r][c]);

            // 每行以分隔符和换行符结束。
            printf("|\n");
        }
    }

    // 释放每个矩阵的内存。
    for (int m = 0; m < NMatrices; ++m)
        free(Matrices[m].Memory);

    // 释放关于矩阵的结构体数组的内存。
    free(Matrices);
}
英文:

Since each matrix may be a different size, you should manage each matrix separately and record its dimensions separately. The code below shows how to use a structure type to do that.

Common C implementations support variable length arrays, so you use this to make addressing the matrix elements simpler. The program below shows how to use a pointer to a variable length array to point to the rows of a matrix. The memory address is recorded in the structure using void *, because we cannot have a variably modified type in the structure, but a separate variable is declared where it is needed, and it is set to the start of memory for the matrix.

In the absence of using variable length arrays, you would have to address the elements using manual arithmetic calculations into a linear array.

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
int main(void)
{
// Read the number of matrices.
int NMatrices;
printf(&quot;Enter the number of matrices:  &quot;);
if (1 != scanf(&quot;%d&quot;, &amp;NMatrices))
{
fprintf(stderr, &quot;Error, scanf for number of matrices failed.\n&quot;);
exit(EXIT_FAILURE);
}
if (NMatrices &lt; 0)
{
fprintf(stderr, &quot;Error, number of matrices is negative.\n&quot;);
exit(EXIT_FAILURE);
}
// Define a type to manage a matrix.
struct MatrixInformation
{
void *Memory;        // Memory for the matrix.
int NRows, NColumns; // Number of rows and number of columns.
};
// Allocate memory to manage NMatrices matrices.
struct MatrixInformation *Matrices = malloc(NMatrices * sizeof *Matrices);
if (!Matrices)
{
fprintf(stderr, &quot;Error, failed to allocate memory.\n&quot;);
exit(EXIT_FAILURE);
}
// Read each matrix.
for (int m = 0; m &lt; NMatrices; ++m)
{
// Read the number of rows and the number of columns of this matrix.
int NRows, NColumns;
printf(&quot;Enter the number of rows in matrix %d:  &quot;, m+1);
if (1 != scanf(&quot;%d&quot;, &amp;NRows))
{
fprintf(stderr, &quot;Error, scanf for number of rows failed.\n&quot;);
exit(EXIT_FAILURE);
}
if (NRows &lt;= 0)
{
fprintf(stderr, &quot;Error, number of rows is not positive.\n&quot;);
exit(EXIT_FAILURE);
}
printf(&quot;Enter the number of columns in matrix %d:  &quot;, m+1);
if (1 != scanf(&quot;%d&quot;, &amp;NColumns))
{
fprintf(stderr, &quot;Error, scanf for number of columns failed.\n&quot;);
exit(EXIT_FAILURE);
}
if (NColumns &lt;= 0)
{
fprintf(stderr, &quot;Error, number of columns is not positive.\n&quot;);
exit(EXIT_FAILURE);
}
// Create a temporary pointer for the matrix and allocate memory.
int (*Matrix)[NColumns] = malloc(NRows * sizeof *Matrix);
if (!Matrix)
{
fprintf(stderr, &quot;Error, failed to allocate memory.\n&quot;);
exit(EXIT_FAILURE);
}
// Save the numbers of rows and columns and the memory address.
Matrices[m].NRows = NRows;
Matrices[m].NColumns = NColumns;
Matrices[m].Memory = Matrix;
// Get the values for the matrix elements.
for (int r = 0; r &lt; NRows; ++r)
for (int c = 0; c &lt; NColumns; ++c)
{
printf(&quot;Enter the element [%d, %d]:  &quot;, r+1, c+1);
if (1 != scanf(&quot;%d&quot;, &amp;Matrix[r][c]))
{
fprintf(stderr, &quot;Error, scanf for element failed.\n&quot;);
exit(EXIT_FAILURE);
}
}
}
// Print each matrix.
for (int m = 0; m &lt; NMatrices; ++m)
{
printf(&quot;Matrix %d:\n&quot;, m+1);
// Get the numbers of rows and columns and the memory address.
int NRows = Matrices[m].NRows;
int NColumns = Matrices[m].NColumns;
int (*Matrix)[NColumns] = Matrices[m].Memory;
// Print each row.
for (int r = 0; r &lt; NRows; ++r)
{
// Start each row with a delimiter and no spaces.
printf(&quot;|%d&quot;, Matrix[r][0]);
// Print each element with two spaces for separation.
for (int c = 1; c &lt; NColumns; ++c)
printf(&quot;  %d&quot;, Matrix[r][c]);
// Finish each row with a delimiter and a new-line character.
printf(&quot;|\n&quot;);
}
}
// Free the memory of each matrix.
for (int m = 0; m &lt; NMatrices; ++m)
free(Matrices[m].Memory);
// Free the memory for the array of structures about the matrices.
free(Matrices);
}

答案2

得分: -2

首先,在C语言中,你不能使用静态数组的语法来创建动态数组。为了理解我的说法,只需在定义数组“k”后添加一个sizeof printf语句,类似于这样:

struct x k[m];
printf("k的大小为%li\n", sizeof k);

正如你所看到的,数组的大小返回为0,因为在编译时,行和列的值都为零。

你应该在堆内动态创建数组,并使用指针将它们连接起来。最好的方法是使用malloc函数。

首先根据矩阵变量的值创建一个指针数组:

int* my_array;
...
my_array = (int*) malloc(matrix * sizeof(int*));

然后,在你的循环中,获取行和列的值,并为每个数组创建新的动态数组:

int* inner_array;
for (int m = 0; m < matrix; m++) {
...
inner_array = (int*) malloc(row * column * sizeof(int));
my_array[m] = inner_array;

最后,使用inner_array来分配每个数组的值。

英文:

first of all, in C you can not make dynamic array with syntax of static array. to understand what I say, just put a sizeof printf after defining array 'k'. something like this

struct x k[m];
printf(&quot;size of k %li\n&quot;, sizeof k);

as you can see, the size of array return az 0. because at the compile time, the value of row and column are zero.

you should create your array dynamically inside heap. and link them using pointers. the best way is to use malloc.


first create an array of pointers based on value of the matrix variable.

int* my_array;
...
my_array = (int*) malloc(matrix)

then in your loop take values of row and column and create new dynamic array for each of them

int* inner_array;
for (int m = 0; m &lt; matrix; m++) {
...
inner_array = (int*) malloc(row * column);
my_array[m] = inner_array;

and finally using inner_array to assign values of each array.

huangapple
  • 本文由 发表于 2023年6月1日 21:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定