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/