我已阅读您的代码,并且我假设您正在尝试通过用户输入构建 2D 地图,这是一个字符串(在您的代码中名为“Line”),应该只包含从 0 到 9 的数字。从 0 开始的数字到 9 可能代表地图的不同元素。我猜对了吗?
我复制并修改了你的代码,最后我得到了这样的结果:
program screenshot
如果我猜对了,我先解释一下你的代码编译不成功的原因。
long long M; char line[M];
在这里,您使用了一个变量来声明数组的大小。此语法适用于其他一些编程语言,但不适用于 C。在 C 中,编译源代码时,编译器必须确切知道要为每个函数分配多少堆栈内存空间(在您的情况下为 main() 函数)。由于编译器在尝试编译代码时不知道数组有多大,因此编译失败。
一种常见的解决方案是,我们选择将数组存储在堆中,而不是将数组存储在堆栈中,因为堆内存是在程序运行时动态分配和释放的。换句话说,您可以在获得用户输入后决定分配多少内存。函数 malloc() 和 free() 用于这种操作。
另一个问题是使用“long long **map”。虽然它不会导致编译失败,但它也不会给你预期的结果。当数组的M(数组宽度)是一个已知的常数值时,我们总是倾向于使用“long long map[][M]”作为参数。但是,在您的情况下,由于 M 未知,常见的解决方案是手动计算目标位置,因为无论数组维度如何,数组中的元素始终以线性顺序存储在内存中。
上述两个问题我已经修复,下面贴上修改后的源码,已经编译成功:
#include <malloc.h>
#include <string.h>
void buildMap(int *map, int i, char * line);
int main()
{
int N;
int M;
scanf("%d%d", &N, &M);
/*Since M (available memory space for "Line") is set by user, we need to build
"szSafeFormat" to restrict the user's input when typing the "Line". Assuming M
is set to 8, then "szSafeFormat" will look like "%7s". With the help of
"szSafeFormat", the scanf function will be scanf("%7s", Line), ignoring
characters after offset 7.*/
char szSafeFormat[256] = { 0 };
sprintf(szSafeFormat, "%%%ds", M - 1);
//char line[M];
char *Line = (char *)malloc(sizeof(char) * M); //raw user input
char *pszValidInput = (char *)malloc(sizeof(char) * M); //pure numbers
//long long map[N][M];
int *pnMap = (int *)malloc(sizeof(int) * M * N);
memset(pnMap, 0xFF, M * N * sizeof(int)); //initialize the Map with 0xFF
for (int i = 0; i < /*M*/N; i++)
{
scanf(szSafeFormat, Line); //get raw user input
sscanf(Line, "%[0-9]", pszValidInput); //only accept the numbers
while (getchar() != '\n'); //empty the stdin buffer
buildMap((int *)(pnMap + i * M), i, pszValidInput);
}
printf("\r\n\r\n");
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
//if the memory content is not 0xFF (means it's a valid value), then print
if (*(pnMap + i * M + j) != 0xFFFFFFFF)
{
printf("%d", *(pnMap + i * M + j));
}
}
printf("\r\n");
}
free(Line);
free(pszValidInput);
free(pnMap);
return 0;
}
void buildMap(int *map, int i, char * line)
{
for (int j = 0; j < strlen(line); j++)
{
(int) *((int *)map + j) = line[j] - '0';
}
}
我使用了类型“int”而不是“long long”,但是如果你坚持继续使用“long long”应该不会有任何问题。如果继续使用“long long”,则打印出数组值时的条件应更改为:
if (*(pnMap + i * M + j) != 0xFFFFFFFF)
到
if (*(pnMap + i * M + j) != 0xFFFFFFFFFFFFFFFF)
还有一些关于用户输入验证的其他修改,我在代码中编写了一些额外的 cmets。