Why don't I need to dereference a character pointer in C before printing it? -
why code work? expect need dereference ptr
, printf("%s\n", *ptr);
before print out, segmentation fault
if try way.
#include <stdio.h> int main(int argc, char *argv[]) { char name[] = "jordan"; char *ptr = name; printf("%s\n", ptr); }
hope guys give me insight.
when print string need starting address of string.
printf("%s\n", ptr); ^ address %s
it prints chars till \0
nul encounter.
whereas print chat int .. need value variable:
printf("%c\n", *ptr); ^ * %c print first char
where in scanf()
string need give address:
scanf("%s", ptr); ^ string address
also int scanf()
char
scanf("%c", ptr); ^ read @ first location char address
note: scanf()
need address %c
store scanned value in memory.
be careful ptr
points constant string can't use in scanf.
why segmentation fault following code ?
printf("%s\n", *ptr);
when this, because of %s
printf interprets *ptr
address, not address , if treat address points location read protected program(process) causes segmentation fault.
your ptr
via name
points constant string in memory ("jordan") in below diagram:
name 2002 ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ │ 'j' │ 'o' │ 'r' │ 'd' │ 'a' │ 'n' │'\0' │ ........ └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ ^ | ptr = name ==> ptr = 2002 *ptr = 'j'
in printf("%s\n", *ptr);
*ptr = 'j'
, ascii value of char 'j' 74
74
address not under process control , trying read memory location , memory violation , segmentation fault occurs.
if compiles code containing printf("%s\n", *ptr);
proper option -wall
gcc
warning below:
warning: format ‘%s’ expects argument of type ‘char *’, argument 2 has type ‘int’
says %s
need (expects ) address of type char*
putting value
notice:
printf("%s\n", *ptr); ^ ^ argument-2 argument-1
Comments
Post a Comment