Program crashes when passing printf to a char array pointer

When I try to run the following code, I get a seg error. I tried to run it through gdb, and I understand that the error occurs as part of the call printf, but I lost why it doesn’t work.

#include <stdlib.h>
#include <stdio.h>

int main() {
  char c[5] = "Test";
  char *type = NULL;

  type = &c[0];
  printf("%s\n", *type);
}

If I replaced printf("%s\n", *type); with printf("%s\n", c);I get the "Test" as I expected. Why doesn't it work with a pointer to a char array?

+5
source share
3 answers

You pass a simple charwhile printftrying to dereference it. Try instead:

printf("%s\n", type);
              ^ 

If you pass *type, then how to say printf, I have a line in place of T ".

Also type = &c[0]misleading. Why don't you just:

type = c;
+15

type. .

+5

Remove the dereferencing typein printf.

+4
source

All Articles