我一直在尝试将遍历树的顺序写入 C 中的 .txt 文件。我没有使用数组,而是使用自己的数据类型 vector 来存储树的节点值。然后,我尝试从 vector 中的项目创建一个字符数组。这个过程按预期进行,但是当我将 char 数组打印到屏幕上时,它在开头打印 5 个随机字符。我确信问题不在 vector 中,而是在其他地方,因为当我尝试打印循环内的字符时,它不会在屏幕上打印任何意外的字符(请参见图片)以下)。我们将非常感谢您帮助发现错误。
NODE* char_tree = optimised_tree(); // First Node of the tree
vector* tree_items = new_vector();
parse_tree(char_tree, tree_items); // parses the tree and add nodes to vector
int len = vec_size(tree_items); // size of the vector
char xs[len + 2];
char x[2];
for (int i = 0; i < len; ++i)
{
int o = vec_get(tree_items, i); // item at index i in vector tree_items
printf("%c ", o);
x[0] = (char)o;
x[1] = '\0';
strcat(xs, x);
}
xs[len] = '\n';
xs[len + 1] = '\0';
printf("\n-> %sSIZE %lu\n", xs, sizeof(xs));
最佳答案
问题是您使用变量xs
而没有初始化它!代码:
char xs[len + 2];
声明一个字符数组,但不为其分配任何内容。因此,您有一个包含任意(=“随机”)内容的字符数组。
要解决您的问题,只需在声明它时将 xs
初始化为空字符串(请参见下面的注释),或者(更好,恕我直言)在开始之前使用如下代码for 循环:
strcpy(xs, "");
注意:您不能使用正常的 initializer syntax on variable length arrays !因此,这样的代码将不起作用:
char xs[len + 2] = ""; // Cannot initialize VLA
但是你可以这样做:
char xs[len + 2]; xs[0] = 0;
关于c - 字符数组开头出现意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918670/