在c中打印锯齿状阵列

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

所以我正在研究在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
c arrays printf jagged-arrays
4个回答
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;


    }

2
投票

argc == 5argv[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


2
投票

使用一些限制性编译器标志,例如--pedantic --std=c11 -Wall -Wextra为gcc。这将帮助您找到包括您自己在内的一些错误。

包括stdlib.h您的malloc()电话。

argv[0]不是你的第一个命令行参数,它是你的二进制文件的名称。所以你必须调整循环。

为了简化没有给出参数的情况,请包含assert.h并使用assert(argc > 1);检查main开头的参数数量。

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


1
投票

错误来源

1> argv[0]必将失败。

2> malloc没有包含库(需要stdlib.h)。

© www.soinside.com 2019 - 2024. All rights reserved.