指针数组C - 空位置

时间:2014-06-29 05:32:04

标签: 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;
}

为什么单词+ 2在循环条件下工作而不是单词或单词+ 1

这是单词array

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

2 个答案:

答案 0 :(得分:3)

您正在遍历words中的指针并检查零 指针,但你没有在数组的末尾添加一个sentinel。试试这个:

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

据推测,words + 2之所以有效,是因为碰巧有些事情发生了 该位置的内存等同于NULL指针。

答案 1 :(得分:0)

为简单起见,我通过注释addToTree函数调用

来修改代码
#include<stdio.h>
#include<stdio.h>

void addToTree(char **);

int main() {

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

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

当我尝试使用*words的代码时,我看到了一个问题。当单词位于数组的最后一个元素时,你仍然将它递增(这很好)并取消引用指针(在循环条件中)。取消引用操作不是很好,因为在实践中,您应该访问显式控制程序的内存位置。我认为检测数组中有多少元素然后只运行多次循环是个好主意。

正如汤姆所说,你刚刚幸运(和我一样),因为似乎在数组的末尾存储了一个NULL。

$ ./treeaddso 

 VALLED 0
 the current word is 3

 VALLED 1
 the current word is 8

 VALLED 2
 the current word is 1

为了更加清晰,请研究该计划的o / p:

#include<stdio.h>
#include<stdio.h>

void addToTree(char **);

int main() {

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

}

void addToTree(char *words[])
{
    int count=0;
    while( *words)
    {
        printf("count is %d\n",count++);
        printf("the current value of words is %p\n",words);
        printf("the current value stored in words is %p\n",*words);
        printf("the character is %c\n",**words);
        words++;
    }
    return;
}

$ ./treeaddso 
count is 0
the current value of words is 0x7fff2ce87de0
the current value stored in words is 0x4006b0
the character is 3
count is 1
the current value of words is 0x7fff2ce87de8
the current value stored in words is 0x4006b2
the character is 8
count is 2
the current value of words is 0x7fff2ce87df0
the current value stored in words is 0x4006b4
the character is 1