你好,需要帮助创建多维数组我是C公司的新员工,如有任何帮助,不胜感激。这是代码
#include <stdio.h>
char init_board(int row, int col);
int main(int argc, char** argv) {
int row = argv[3];
int col = argv[4];
char** board = init_board(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d", board[i][j]);
}
}
return 0;
}
char init_board(int row, int col) {
int count = 0;
int count2 = 0;
char** out;
while (count < row) {
while (count2 < col) {
out[count][count2] = ".";
count2++;
}
count++;
count2 = 0;
}
return out;
}
知道我该怎么解决吗?我做错了什么?当我编译时,我会收到以下警告,当我运行时,它会显示分段错误
s@ss:~/s216/arc/ass1/ass1$ gcc ass1.c -std=c99 -o test
ass1.c: In function ‘main’:
ass1.c:6:12: warning: initialization makes integer from pointer without a cast [enabled by default]
int row = argv[3];
^
ass1.c:7:12: warning: initialization makes integer from pointer without a cast [enabled by default]
int col = argv[4];
^
ass1.c:8:17: warning: initialization makes pointer from integer without a cast [enabled by default]
char** board = init_board(row, col);
^
ass1.c: In function ‘init_board’:
ass1.c:27:23: warning: assignment makes integer from pointer without a cast [enabled by default]
out[count][count2] = ".";
^
ass1.c:33:2: warning: return makes integer from pointer without a cast [enabled by default]
return out;
^
s@ss:~/s216/arc/ass1/ass1$ ./test x x 5 5
Segmentation fault
s@ss:~/s216/arc/ass1/ass1$
argv[3]
和argv[4]
的类型为char*
。因此,线
int row = argv[3];
int col = argv[4];
是错误的。您正试图用char*
初始化两个int
对象。
如果您使用运行程序
program 10 20 30 40
然后,
argv[0]
的值将为"program"
argv[1]
的值将为"10"
argv[2]
的值将为"20"
argv[3]
的值将为"30"
argv[4]
的值将为"40"
。
是的,它们看起来像是命令行中的数字,但它们是C程序中的字符串。您可以使用atoi
从字符串中提取整数。
int row = atoi(argv[3]);
int col = atoi(argv[4]);
确保使用
#include <stdlib.h>
以获取函数的声明。
当您编写int row = argv[3];
时,您正在生成一个int并将其初始化为argv[3]
的值。然而,argv
的类型是char **
,它是指向指针的指针,或者实际上是char *
类型的数组。这是一个无效的赋值,您需要制作一个char缓冲区来读取中的参数,然后使用atoi(argv[i])
来获取整数值。
最初代码有很多错误,我相信下面的代码是应该的。。
#include <stdio.h>
#include <stdlib.h>
char **init_board(int row, int col);
int main(int argc, char** argv) {
int row = atoi(argv[3]);
int col = atoi(argv[4]);
char** board = init_board(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
board[i][j] = 'x';
printf("%c", board[i][j]);
}
}
return 0;
}
char **init_board(int row, int col) {
char** out = malloc(sizeof(char*) * row);
for (int i = 0; i < row; i++)
out[i] = malloc(sizeof(char) * col);
return out;
}