C 声明矩阵变量,并将变量声明为索引

问题描述 投票:0回答:1

我想知道是否可以在 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 物理,所以我不能尝试太多其他事情来尝试解决这个问题。

c matrix
1个回答
0
投票

如果您不知道矩阵有多少行,则使用指向数组的指针。

    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;

您的数组将只有一个内存块 - 与“普通”数组相同。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.