WhiteHotLoveTiger
WhiteHotLoveTiger

Reputation: 2238

Program crashes when I give printf a pointer to a char array

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?

Upvotes: 5

Views: 8284

Answers (3)

Adam S
Adam S

Reputation: 3125

Remove the dereferencing of type in your printf.

Upvotes: 4

Phonon
Phonon

Reputation: 12737

Don't dereference type. It must remain a pointer.

Upvotes: 5

cnicutar
cnicutar

Reputation: 182734

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;

Upvotes: 15

Related Questions