When I try to run the following code I get a seg fault. I've tried running it through gdb, and I understand that the error is occurring as part of calling printf
, but I'm lost as to why exactly it isn't working.
#include <stdlib.h>
#include <stdio.h>
int main() {
char c[5] = "Test";
char *type = NULL;
type = &c[0];
printf("%s\n", *type);
}
If I replace printf("%s\n", *type);
with printf("%s\n", c);
I get "Test" printed as I expected. Why doesn't it work with a pointer to the char array?
You're passing a plain char
and printf
is trying to dereference it. Try this instead:
printf("%s\n", type);
^
If you pass *type
it's like telling printf
"I've got a string at location T".
Also type = &c[0]
is kind of misleading. Why don't you just:
type = c;
Don't dereference type
. It must remain a pointer.
Remove the dereferencing of type
in your printf
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With