c - 指针递增到 NULL 直到字符串结尾如下代码但是如果检查它证明是错误的为什么?

标签 c string pointers strdup

Hi 指针递增到 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
        }
    }

最佳答案

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

一个有效的指针不会通过简单的指针运算变成空指针。它可能指向边界之外,但它不会变为 NULL

这里发生的是 temp 是单字符字符串 ","。这与包含两个字符 ',''\0' 的数组相同。当您执行 *temp++ = '\0' 时会发生什么,您将字符串修改为两个字符 '\0' 后跟 '\0' (您将 ocmma 替换为字符串终止符)。运行后temp指向第二个'\0'。变量 temp 本身不是空指针,但它指向空字符(这是完全不同的东西)。

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

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

如果再“图形化”一点,可能会更容易理解。

创建重复字符串时

temp = strdup(q);

你会得到这样的东西

----+-----+------+----
... | ',' | '\0' | ...
----+-----+------+----
    ^
    |
    +------+
    | temp |
    +------+

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

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

----+------+------+----
... | '\0' | '\0' | ...
----+------+------+----
           ^
           |
           +------+
           | temp |
           +------+

关于c - 指针递增到 NULL 直到字符串结尾如下代码但是如果检查它证明是错误的为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069717/

相关文章:

c - 我的C加密程序有什么问题?

python - 可迭代预期的原始文本文档,接收到字符串对象

C++:C++11 能否移动语义以避免共享所有权情况下的指针?

c++ - 在 C/C++ 中取消引用 char 指针?

使用线程并发下载文件

c - uPP 设备驱动程序正在从缓冲区中删除数据

c - 如何实现格式化功能

c++ - 如何将字符串添加到 char 元素的二维数组中?

iphone - 在 Objective-C 中将单个字符串分成两个不同的字符串

c++ - 回到指针位置