所以我正在研究在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
你需要包括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;
}
argc == 5
和argv[0]
包含./jagged
。
atoi
将因argv[0]
而失败,其错误行为未定义。如果程序继续,则返回0,并将0作为长度之一存储。这意味着你将执行malloc(sizeof(int) * 0);
,这也可能导致麻烦。
要解决这些问题,您有两种选择:
i = 1; i < argc; i++
循环以避免argv[0]
。--argc, ++argv;
或argc
之前添加一行argv
。您还应该考虑使用strtol
而不是atoi
,因为它具有明确定义的错误行为。
除了你的程序逻辑,你只是忘了包括<stdlib.h>
能够使用malloc
和atoi
as @Vishal explained。
使用一些限制性编译器标志,例如--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> argv[0]
必将失败。
2> malloc
没有包含库(需要stdlib.h
)。