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 ofchar
, which is in fact a\0
terminated string. This string can be printed withprintf("%s", p);
- Since
p
is a pointer you can print the memory address it points toprintf("%p", p);
, which is exactly the same as ifp
was defined asvoid *p;
*p
dereferences the firstchar
in the string pointed to byp
, which is essentially the same asp[0]
. This string can be printed withprintf("%c", *p);
orprintf("%c", p[0]);