Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 784
WhiteHotLoveTiger Avatar asked Feb 21 '12 19:02

WhiteHotLoveTiger


3 Answers

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;
like image 142
cnicutar Avatar answered Nov 24 '22 01:11

cnicutar


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

like image 31
Phonon Avatar answered Nov 24 '22 00:11

Phonon


Remove the dereferencing of type in your printf.

like image 33
Adam S Avatar answered Nov 24 '22 01:11

Adam S