在c

时间:2018-09-14 03:54:04

标签: c arrays printf jagged-arrays

所以我正在用C制作一个锯齿状的数组。我认为我的代码可以填充数组,但是我遇到的问题是打印。

下面的代码

#include <stdio.h>

int *length;
int **row;

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

    //make an array that contains the lengths of the columns for each row
    length = malloc(argc * sizeof (int));
    for (int k = 0; k < argc; k++) {
        length[k] = atoi(argv[k]);
       // printf("%d ", lengths[k]);
    }
    row = malloc(argc * sizeof (int));

    // fill the columns
    int fill = 1;
    for (int i = 0; i < argc; i++) {
        row[i] = malloc(sizeof (int) * length[i]);
        for (int j = 0; j < length[i]; j++)
            row[i][j] = fill;

    }

    //print it
    for (int i = 0; i < argc; i++)
        for (int j = 0; j < length[i]; j++)
            printf("%d", row[i][j]);

    return 0;


}

该程序采用命令行参数,因此如果我输入:

./jagged 1 3 5 1

我应该得到:

1
1 1 1
1 1 1 1 1
1

相反,我的编译器只是说

RUN FAILED

3 个答案:

答案 0 :(得分:2)

argc == 5,而argv[0]包含./jagged

atoi对于argv[0]将失败,并且其错误行为未定义。如果程序继续,则返回的值是0,并且您将0作为长度之一存储。这意味着您将执行malloc(sizeof(int) * 0);,这也可能会引起麻烦。

要解决这些问题,您有两种选择:

  1. i = 1; i < argc; i++中回避以避免argv[0]
  2. 在使用--argc, ++argv;argc之前,添加一行argv

您还应考虑使用strtol代替atoi,因为它具有明确的错误行为。

除了程序逻辑之外,您只是忘记包含<stdlib.h>以便能够使用mallocatoi as @Vishal explained

答案 1 :(得分:2)

使用一些限制性的编译器标志,例如--pedantic --std=c11 -Wall -Wextra代表gcc。这将帮助您发现一些错误,例如缺少自己。

在呼叫stdlib.h时包括malloc()

argv[0]不是您的第一个命令行参数,而是二进制文件的名称。因此,您必须调整循环。

要简化未给出任何参数的情况,请包含assert.h,并使用assert(argc > 1);检查主行开头的参数数量。

您对row的分配不正确,但依赖于平台,因为row的元素类型为int *,而不是int。而是分配row = malloc((argc - 1) * sizeof(int *));

答案 2 :(得分:1)

您需要包括stdlib才能使用malloc功能并在第一个程序段之后打印\ n

    #include <stdio.h>
    #include <stdlib.h>
    int *length;
    int **row;

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

        //make an array that contains the lengths of the columns for each row
        length = malloc(argc * sizeof (int));
        for (int k = 0; k < argc; k++) {
            length[k] = atoi(argv[k]);
           // printf("%d ", lengths[k]);
        }
        row = malloc(argc * sizeof (int));

        // fill the columns
        int fill = 1;
        for (int i = 0; i < argc; i++) {
            row[i] = malloc(sizeof (int) * length[i]);
            for (int j = 0; j < length[i]; j++)
                row[i][j] = fill;

        }

        //print it
        for (int i = 0; i < argc; i++)
        {
            for (int j = 0; j < length[i]; j++){
                printf("%d", row[i][j]);
            }
            printf("\n");
        }

        return 0;


    }
相关问题