如何初始化大小由argc和argv确定的2D数组? [英] How to initialize a 2D array in which the size is determined by argc and argv?

查看:92
本文介绍了如何初始化大小由argc和argv确定的2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究代码,该代码将跟踪每次访问数组中特定元素的时间。数组本身将根据用户的输入动态分配,因此,我所寻找的功能都不是我想要的。更具体地说,如何动态分配数组的行和列,然后将每个元素初始化为0?
Ex。

./SIM AB

I am working on code which will keep track of each time a specific element in an array is accessed. The array itself will be allocated dynamically based off of the inputs by the user, and so no functions that I have seen are what I'm looking for. To be more specific, how do I dynamically allocate the rows and columns of an array, and then initialize every element to 0? Ex.
./SIM A B

int* array_columns = malloc(atoi(argv[1]) * sizeof(int));
int* array_rows = malloc(atoi(argv[2]) * sizeof(int)); 
int array[*array_rows][*array_columns];

我所看到的所有内容都需要事先知道每一行/列中的元素数量。谁能提供任何有关如何将此数组初始化为0的指针?编辑:我在试图建立数组的行中添加了行

everything that I have seen requires knowing beforehand the number of elements in each row/column. Can anyone give any pointers on how to initialize this array to 0? edit: I have added the line where I attempt to establish the array

推荐答案

该程序使用命令行参数分配内存并创建一个可以使用数组语法访问的变量。它使用 calloc 将值初始化为零:

This program allocates memory using command line parameters and creates a variable that can be accessed using array syntax. It uses calloc to initialize values to zero:

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


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

    int length = atoi(argv[1]);
    int width = atoi(argv[2]);

    array = calloc(length, sizeof(int *));
    for (int i = 0; i < length; i++) {
        array[i] = calloc(width, sizeof(int));
    }

    for (int i = 0; i < length; i++) {
        for (int j = 0; j < width; j++) {
            printf("array[%d][%d] = %d\n", i, j, array[i][j]);
        }
    }

    for (int i = 0; i < length; i++) {
        free(array[i]);
    }
    free(array);

    return 0;
}

已编译

gcc -Wall -Werror -o scratch scratch.c

输出

[user@machine]: ./scratch 3 5
array[0][0] = 0
array[0][1] = 0
array[0][2] = 0
array[0][3] = 0
array[0][4] = 0
array[1][0] = 0
array[1][1] = 0
array[1][2] = 0
array[1][3] = 0
array[1][4] = 0
array[2][0] = 0
array[2][1] = 0
array[2][2] = 0
array[2][3] = 0
array[2][4] = 0

注意

我省略了输入验证和错误检查,以使示例不多。

I left out input validation and error checking to keep the example small.

编译器选项

我使用 -Wall -Werror 打开所有警告并将其视为错误。这意味着除非所有警告原因都已解决,否则编译器将不会生成可执行文件。 -o scratch 告诉编译器如何命名输出文件。

I use -Wall -Werror to turn on all warnings and treat them as errors. This means the compiler won't produce an executable unless all the causes of warnings are fixed. The -o scratch tells the compiler what to name the output file.

这篇关于如何初始化大小由argc和argv确定的2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆