user3588044 user3588044 - 1 month ago 6
C Question

Pointer is increment to NULL till end of string as bellow code but while if check its prove to be wrong why?

Hi pointer is increment to NULL to the end of string as bellow code but while if check its prove to be wrong why?

#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 incremenet 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
}
}

Answer

The only way you could increase a pointer and get it to be NULL would be if you loop enough so the pointer address wraps and become zero. Or if you subtract the pointer from itself so the result becomes zero.

A valid pointer will otherwise not become a null pointer by simple pointer arithmetic. It might point out of bounds, but it will not become NULL.

What happens here is that temp is the one-character string ",". This is the same as an array containing the two characters ',' and '\0'. What happens when you do *temp++ = '\0' is that you modify the string to become the two characters '\0' followed by '\0' (you replace the ocmma with the string terminator). After the operation temp points to the second '\0'. The variable temp is itself not a null pointer, but it points to the null character (which is something completely different).

In other words what you possibly want might be something like this:

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

It might be easier to understand if we look at it a little more "graphically".

When you create the duplicate string

temp = strdup(q);

you will have something like this

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

I.e. the variable temp points to a memory location which happens to be the "string" containing a single comma.

When you do *temp++ = '\0' what first happens is that you replace the comma that temp points to, then increases the pointer, which means it will look like this instead:

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