我想知道您将如何执行以下操作:
我提供网格的宽度和高度作为命令行参数,现在我需要从标准输入中读取网格并将其存储到2d数组中。如果命令行参数只是标准整数,并且网格格式如下:
1 2 3 4 5 6 ... x
1 2 3 4 5 6 ... x
1 2 3 4 5 6 ... x
. . . . . . ... x
y y y y y y y y
我将如何阅读?我真的很困惑,因为我没有固定的行和列数,因为每个行和列的值都可以根据用户输入而更改。
如果您的问题是有关使用命令行参数创建网格的,那么实际上,正如JohnG所说,参数是静态的,因此宽度和高度是静态的,您可以简单地创建一个数组。
说您的程序使用./program heigth width
格式运行,只需要使用:
int tab[atoi(argv[1])][atoi(argv[2])];
但是,如果要动态创建二维数组(意味着您事先不知道其宽度和高度),下面是一个示例,该示例使用malloc
和指针,这是指针的两个非常重要的部分C语言。请注意,这不完全是一个二维数组,而是一个1D指针数组和几个1D int数组。
#include <stdio.h>
#include <stdlib.h>
int main () {
printf("Height: ");
int height = 0;
scanf("%d", &height);
printf("Width: ");
int width = 0;
scanf("%d", &width);
int** tab = malloc(height*sizeof(int*)); // Take the space for height * pointers of integer that points towards the first values of each line
for (int i = 0; i < height; i++) {
tab[i] = malloc(width*sizeof(int)); // take the space for width * integers, where we will stock our values
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
tab[i][j] = j + 1; // assign the value 1, 2, 3... to each line
}
}
// Print array:
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("%d ",tab[i][j]);
}
printf("\n");
}
// Free memory allocated for each malloc
for (int i = 0; i < height; i++) {
free(tab[i]);
}
free(tab);
return 0;
}