我想知道是否可以在 C 编程语言中声明一个二维矩阵,并将第二个索引声明为变量。不使用 argv[n] 命令行。 例如
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv){
int a;
scanf("%d", &a);
int matrix[][a];
…SNIP…
我正在学习 C 物理,所以我不能尝试太多其他事情来尝试解决这个问题。
如果您不知道矩阵有多少行,则使用指向数组的指针。
size_t cols;
scanf("%zu", &cols);
int (*matrix)[cols];
/* later in the code you need to decide how many words you need */
size_t rows;
scanf("%zu", &rows);
matrix = malloc(rows * sizeof(*matrix));
/* you can change it using realloc -*/
分配后,您可以使用普通数组方式 - 例如:
matrix[3][4] = 345643;
您的数组将只有一个内存块 - 与“普通”数组相同。