使用输入将数组大小放在一行中

时间:2017-11-29 19:24:49

标签: c matrix input

我一直试图创建一个动态的二维矩阵,用户可以根据输入给出矩阵的大小。 例如:3 1 2 3 4 5 6 7 8 9,其中第一个int 3是矩阵的大小(3 * 3),其余的数字是I' d想要在我的矩阵中输入的数字。 任何想法怎么做?

2 个答案:

答案 0 :(得分:1)

如果"动态"只是意味着在运行时定义了2d矩阵的大小,那么您可以使用可变长度数组。这些是在功能范围内创建的,并且是真实的" 2D阵列在某种意义上是n x n连续存储的整数,可以像array[x][y]那样访问。请参阅以下代码说明此方法:

int main() {

    int n;
    if (scanf("%d", &n) != 1 || n <= 0) {
        printf("invalid input.");
        return 1;
    }

    int array[n][n]; // variable length array
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (scanf("%d", &array[i][j]) != 1) {
                printf("invalid input.");
                return 1;
            }
        }
    }

    // matrix is available in main...
    return 0;
}

如果&#34;动态&#34;但是,意味着使用malloc动态分配,那么你有两次机会,两者都没有导致真正的&#34; 2D阵列:

首先,(动态地)创建一个指针数组,每个条目指向一个(动态)分配的int数组。优点:您可以像arr[x][y]一样访问它;缺点:行不是贪婪地存储,而是(可能)在内存中传播。

其次,(动态)创建一个大小为n * n的整数数组;优点:值存储在连续的内存块中;缺点:您无法像arr[x][y]那样访问它,而是必须自己计算单元格的位置,即arr[y * n + x];

答案 1 :(得分:0)

这就是你要找的东西。 代码在代码中的注释中进行了解释。

阅读here,如何在c中制作动态二维数组。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n;

    scanf("%d", &n);

    /* It will allocate an array of pointers with n elements*/
    int **arr = (int**)malloc(n*sizeof(int*));

    /* each element in the above array would contain another array that makes the upper array as the 2D array */
    for (int i = 0; i < n; i++)
        arr[i] = (int*)malloc(n * sizeof(int));

    /*It is taking the input to put inside the array */
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            scanf("%d", &arr[i][j]);

    /* This is printing the content inside the array */
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            printf("%d\t", arr[i][j]);

    return 0;

}