I want to display "string pointer affected" but I get an error. Here is my code:
#include<stdio.h>
main()
{
char* *p;
char * s="string pointer affected";
*p=s;
printf("%s",*p);
}
I want to display "string pointer affected" but I get an error. Here is my code:
#include<stdio.h>
main()
{
char* *p;
char * s="string pointer affected";
*p=s;
printf("%s",*p);
}
p
doesn't point to any known location, so writing to *p
is a bad idea.
You mean to say:
p = &s;
You dereference a pointer which is not initialized , which will cause undefined behaviour . This is problem -
*p=s;
You are using an uninitialized variable in the line below and in the printf
statement. If you replace
*p = s;
with
p = &s;
then it will work.
Try:
#include<stdio.h>
main()
{
char *p; // <--------------------------
char *s="string pointer affected";
printf("===== s=%p\n", s);
p=s;
printf("===== p=%p\n", p);
printf("%s\n", p);
}
The problem with the original code is that p
is uninitialized. So you cannot dereference it.
If you do want to use a pointer to a pointer, allocate the pointer first, and then take its address.
#include<stdio.h>
main()
{
char *q;
char **p = &q;
char *s="string pointer affected";
*p=s;
printf("%s\n", *p);
}