使用scanf填充多维数组(C语言)

Using scanf to fill out a multidimensional array (C language)

我想知道如何正确使用 scanf 来填充多维数组。

这是我的代码:

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

int main(int argc, const char * argv[]) {

int n; //number of rounds
int* sArray; //multidimensional array that holds the scores of both players
int i;

scanf("%d", &n);

sArray = (int*) calloc (n * 2, sizeof(int));


for(i=0; i<n; i++) {
    scanf("%d %d", &sArray[i][1], &sArray[i][2]); 

}

return 0;
}

它给我一个错误,"Subscripted value is not an array, pointer, or vector."任何帮助将不胜感激!

二维数组定义如下:int sArray[N][M],但由于您想使用动态内存,我建议您看一下指向 int 处的指针的指针:

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

int main()
{
    int n;
    scanf("%d", &n);
    int **sArray;
    sArray = (int **)malloc(n * sizeof(int *));

    int i;
    for(i = 0; i < n; i++)
    {
        sArray[i] = (int *)malloc(2 * sizeof(int));
        scanf("%d %d", &sArray[i][1], &sArray[i][2]);
    } 
    return 0;
}

完成数组后不要忘记clean-up。

如评论中所述,如果使用 pure c,则无需转换 malloc 的结果。我这样做是因为我的 C++ 编译器拒绝在没有这个转换的情况下编译它。

您可能需要在动态分配数组期间检查错误。阅读更多 here

通常要填充一个二维数组,您将使用两个嵌套的 for 循环。 例如:

int array[2][3] = {0};

for (i = 0; i < 2; i++)
   for (k = 0; k < 3; k++)
      scanf("%d", &array [i][k]);

你也可以这样做:

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

int main(int argc, const char * argv[]) {


    int n; //number of rounds
    int** sArray = malloc(2 * sizeof(int*)); //multidimensional array that holds the scores of both players
    scanf("%d", &n);
    sArray[0] = (int*)calloc(n , sizeof(int));
    sArray[1] = (int*)calloc(n , sizeof(int));

    int i;
    for (i = 0; i < n; i++) {
        scanf("%d %d", &sArray[0][i], &sArray[1][i]);
    }

    free(sArray[0]);
    free(sArray[1]);
    free(sArray);

    return 0;
}

这里已经有很多关于如何定义动态二维数组的好答案。但是这个变体还没有被提及,所以我把它记录下来。

由于数组的最后一个维度是固定的,您可以按如下方式定义二维数组:

int (*sArray)[2]; //multidimensional array that holds the scores of both players
...
sArray = (int(*)[2]) calloc (n, sizeof(int)*2);  // self explaining

这样,所有的元素将被连续存储(分配数组的每个n个元素,是2个连续的整数),而不需要数组到数组。

其余代码保持不变。除了你应该解决 sArray[i][0]..[1] 而不是 [1][2] 并在最后释放内存。在 C 中,数组索引总是从 0 开始,到 size-1。

当然,这种方法严格限于最后一个维度固定的二维数组。

Live demo with addressing