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