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
charandprintfis trying to dereference it. Try this instead:If you pass
*typeit’s like tellingprintf“I’ve got a string at location T”.Also
type = &c[0]is kind of misleading. Why don’t you just: