c - 指针数组 C - NULL POSITION

标签 c arrays pointers

我正在尝试使用此函数将节点添加到树中。我使用字符指针数组作为输入数据。为了插入,我每次都会增加指针。

node addToTree(node root , char *words[])
{
int count=0;
while( *(words+2))
{
    printf("\n VALLED %d",count++);
    root=addNode(root,*words);
    printf("\n the current word is %s",*words);
    words++;
}
return root;
}

为什么循环条件中words+2有效,而words或words+1无效

这是单词数组

char *words[3]={"3","8","1"};

最佳答案

您正在迭代 words 中的指针并检查是否为零 指针,但您没有在数组末尾添加哨兵。试试这个:

char *words[] = {"3", "8", "1", NULL};
...
while (*words)

大概,words + 2 起作用是因为碰巧有一些东西 该位置的内存相当于 NULL 指针。

关于c - 指针数组 C - NULL POSITION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473443/

相关文章:

c - Hackerrank 圆形阵列旋转分割错误

谁能建议我对我的代码进行必要的更改?

c - FAT 文件系统和大量写入

c - 位域中的枚举 - ANSI C

javascript - 使用概率循环遍历项目数组

c - 数组的内存映射

C 回显用户输入

jquery - Javascript 按值对数组进行排序

C 值数组,指针段错误

c++ - std::list of pointers 在条目删除时变得无效