我正在尝试调试代码,据我理解,其等效于以下内容...
输出结果现在是正确的。有人能解释一下发生了什么吗?(这段代码基于K&R第6章练习3)。
printf("outside function: %d %d\n", node->ns, node->ns[0]);
function(node->ns);
void function(int *ns) {
printf("inside function: %d %d\n", ns, ns[0]);
}
输出:
outside function: 11532860 1
inside function: 11532860 11532872
这是否是预期结果,还是我的代码解释有误?"11532872"这个数字有点可疑。
更新
问题已经解决!问题出在节点结构的创建上。
原始版本中,function()
(来自上面的片段)等于_contains()
:
typedef struct TreeNode {
char *word;
int lines;
int *line_numbers;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode *allocate_tree_node(void) {
return (TreeNode *) malloc(sizeof(TreeNode));
}
TreeNode *create_tree_node(char *word, int line) {
int line_numbers[MAX_LINES_PER_WORD]; // <--- the problem
TreeNode *node = allocate_tree_node();
node->line_numbers = line_numbers; // <--- the problem
*node->line_numbers = line;
node->lines = 1;
node->word = duplicate_string(word);
node->left = node->right = NULL;
return node;
}
int _contains(int *ns, int n, int size) {
int i;
printf("contains: %d %d %d\n", ns, ns[0], *ns);
for (i = 0; i < size; i++) {
printf("line: %d, index: %d, val: %d\n", n, i, ns[i]);
if (ns[i] == n) {
return 1;
}
}
return 0;
}
TreeNode *add_tree(TreeNode *node, char *word, int line) {
int comparison;
if (node == NULL) {
return create_tree_node(word, line);
}
comparison = strcmp(word, node->word);
if (comparison == 0 && !_contains(node->line_numbers, line, node->lines)) {
printf("not contains: %d %d\n", node->line_numbers, node->line_numbers[0]);
node->line_numbers[node->lines] = line;
node->lines++;
}
else if (comparison < 0) {
node->left = add_tree(node->left, word, line);
}
else {
node->right = add_tree(node->right, word, line);
}
return node;
}
使用malloc而不是数组赋值的修正版本:
TreeNode *create_tree_node(char *word, int line) {
TreeNode *node = allocate_tree_node();
node->line_numbers = malloc(MAX_LINES_PER_WORD * (sizeof node->line_numbers));
*node->line_numbers = line;
node->lines = 1;
node->word = duplicate_string(word);
node->left = node->right = NULL;
return node;
}
输出结果现在是正确的。有人能解释一下发生了什么吗?(这段代码基于K&R第6章练习3)。
"%p"
而不是"%d"
来打印指针。 - aschepler