I am trying to print a string read into the program from the user.
I need to be able to print the string by using a pointer.
Here is a simplified version of my code.
#include <stdio.h>
int main(void)
{
char string[100];
printf("Enter a string: ");
scanf("%s", string);
char *pstring = &string;
printf("The value of the pointer is: %s", *pstring);
return 0;
}
But I am getting a segmentation fault
Can someone please explain why this is happening?
CodePudding user response:
You don't usually take an address of an array, it's either &string[0]
or just string
. In the printf()
for %s
you should pass a char
pointer not a char
(which is what *pstring
is). It's a good idea to add a newline to the printf()
format string as scanf()
doesn't pass that along:
#include <stdio.h>
int main(void) {
char string[100];
printf("Enter a string: ");
scanf("