Home > Software engineering >  char *p and getenv method signature
char *p and getenv method signature

Time:08-05

The method signature for getenv char *getenv(const char *name) The return value is a pointer to char .

Now if we look at the below example :

#include <stdio.h>
#include <stdlib.h>
int main() 
{
  
char *p;
p = getenv("PATH");
if(p != NULL)
 printf("Current path is %s", p);

return 0;


}

The only confusion here is the "p" printed with format specifier "%s" as String but what about the Pointer Dereference If I put "*p" instead, I end up with segmentation fault while if I want to get the pointer address I can do this printf("%p", p); confusion about getting the value by deferencing the point "p" in our case. Please explain

CodePudding user response:

Looks like you're confused about some fundamental basics in C.

In case of

char *p;
  • p is a pointer to a series of char, which is in fact a \0 terminated string. This string can be printed with printf("%s", p);
  • Since p is a pointer you can print the memory address it points to printf("%p", p);, which is exactly the same as if p was defined as void *p;
  • *p dereferences the first char in the string pointed to by p, which is essentially the same as p[0]. This string can be printed with printf("%c", *p); or printf("%c", p[0]);
  • Related