我正在做一个小项目,我正在尝试制作一个二维字符数组。我以前用 int 做过,并试图摆脱那个例子,但似乎我遇到了一个我不明白的问题。
我是这样做的:
adjMatrix = (char **) malloc(sizeof(char *) * dimensions);
for (int i = 0; i < dimensions; i++)
adjMatrix[i] = (char *) malloc(sizeof(char) * (dimensions + 2));
for (int i = 0; i < dimensions; i++)
for (int j = 0; j < (dimensions + 2); j++)
adjMatrix[i][j] = '0';
这是我的显示功能:
for (int i = 0; i < dimensions; i++)
{
for (int j = 0; j < (dimensions + 2); j++)
printf("%s ", &(adjMatrix[i][j]));
printf("\n");
}
这是我的输出
000000 00000 0000 000 00 0
000000 00000 0000 000 00 0
000000 00000 0000 000 00 0
000000 00000 0000 000 00 0
谁能向我解释为什么它会这样显示,并就如何让它在每个插槽中只显示一个“0”提供任何建议?
最佳答案
Could anyone explain to me why it's showing that way and give any advice as to how to make it just a single '0' in each slot?
这是因为您建议打印一个字符串而不是单个字符。
将您的代码更改为:
printf("%c ", adjMatrix[i][j]);
注意,adjMatrix[i]
指向单个字符数组,字符数组是一个字符串。此外,这是未定义的行为,因为您没有 0 终止“字符串”。
&adjMatrix[i][0]
是指向'0' '0' '0' '0' '0' '0'
的指针,
&adjMatrix[i][1]
是指向'0' '0' '0' '0' '0'
的指针,
&adjMatrix[i][2]
是指向'0' '0' '0' '0'
的指针,
...
关于c - 在 C 中分配二维字符矩阵的奇数输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52800511/