the first block
#include <stdio.h> const int max = 3; int main() { int var[] = { 10, 100, 200 }; int i, *ptr[max]; (i = 0; < max; i++) { ptr[i] = &var[i]; /* assign address of integer. */ } (i = 0; < max; i++) { printf("value of var[%d] = %d\n", i, *ptr[i]); } return 0; }
easy understand, since ptr array of int pointers. when need access i
-th element, need dereference value *ptr[i]
.
now second block, same, points array of char
pointer:
#include <stdio.h> const int max = 4; int main() { char *names[] = { "zara ali", "hina ali", "nuha ali", "sara ali", }; int = 0; (i = 0; < max; i++) { printf("value of names[%d] = %s\n", i, names[i]); } return 0; }
this time, when need access element, why don't add *
first?
i tried form correct statement print value, seems if dereference, single char. why?
printf("%c", *names[1]) // z
i know there no strings in c, , char
array. , know pointers, still don't under syntax here.
for printf()
%s
format specifier, quoting c11
, chapter §7.21.6.1
s
if nol
length modifier present, argument shall pointer initial element of array of character type. [...]
in case,
printf("value of names[%d] = %s\n", i, names[i] );
names[i]
is pointer, required %s
. why, don't dereference pointer.
fwiw,
%c
expectsint
type argument (converted unsigned char,), need dereference pointer value.%d
expectsint
argument, have go ahead , dereference pointer, mentioned in question.
Comments
Post a Comment