0

嗨指针递增到 NULL 到字符串的末尾,如下面的代码,但是如果检查它证明是错误的,为什么?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char *p="Hello,"; // after comma NULL is implicit here
    char *q;
    q=strchr(p,',');  // copyied all char from , till null
    printf("%s\n",q); // good its print , 
    char *temp=strdup(q); // temp contain all string of q
    printf("%s\n",temp); // , good
    if(temp!=NULL)
    {
        *temp++='\0'; // overwriting , with NULL and increment pointer which now point to NULL
        printf("%s\n",temp); // blank because it is NULL
        if(temp==NULL) // bad why this is not true since pointer temp is pointing to NULL?
        {
            printf("its null\n");  // why i am not getting this
        }
    }
4

1 回答 1

4

您可以增加指针并使其成为的唯一方法NULL是,如果您循环足够多,以使指针地址回绕并变为零。或者,如果您从自身中减去指针,则结果为零。

否则,通过简单的指针运算,有效指针将不会变为空指针。它可能会越界,但不会变成NULL.

这里发生的temp是一个字符的字符串","','这与包含两个字符和的数组相同'\0'。当您这样做时*temp++ = '\0',您将字符串修改为'\0'后面的两个字符'\0'(您将 ocmma 替换为字符串终止符)。操作后temp分到第二个'\0'。该变量temp本身不是空指针,但它指向空字符(这是完全不同的东西)。

换句话说,您可能想要的可能是这样的:

*temp++ = '\0';
if (*temp == '\0') { ... }

如果我们更“图形化”地看待它,可能会更容易理解。

创建重复字符串时

temp = strdup(q);

你会有这样的东西

-----+-----+------+----
... | ',' | '\0' | ...
-----+-----+------+----
    ^
    |
    +------+
    | 温度 |
    +------+

即变量temp指向的内存位置恰好是包含单个逗号的“字符串”。

当您这样做*temp++ = '\0'时,首先发生的是替换temp指向的逗号,然后增加指针,这意味着它将看起来像这样:

-----+--------+------+----
... | '\0' | '\0' | ...
-----+--------+------+----
           ^
           |
           +------+
           | 温度 |
           +------+
于 2016-10-16T11:38:05.527 回答