Quoc Anh Pham
Quoc Anh Pham

Reputation: 11

pointer in array of pointer print value without *

#include<stdio.h>
#include<string.h>

int main()
{
 char arr[3][10];
 char *ptr[3];
 strcpy(arr[1],"abcde");
 ptr[1]=arr[1];
 printf("%s\n",arr[1]);
 printf("%p\n", &arr[1]);
 printf("%p\n", ptr[1]);
 printf("%p\n", &ptr[1]);
 printf("%s\n",ptr[1]);
 printf("%s\n", *(ptr+1));
 return 0;
}

Result

abcde
0x7ffdcbbd8daa
0x7ffdcbbd8daa
0x7ffc30ed1188
abcde
abcde

I know ptr is an array of pointer. Dereferencing a pointer needs a unary operator before it. Why can we dereference the pointer ptr[1] without the *? Thanks

Upvotes: 1

Views: 70

Answers (2)

gsamaras
gsamaras

Reputation: 73366

You got it wrong. Here:

printf("%s\n", ptr[1]);
  • The format %s expects a pointer to char.
  • ptr[1] is a char pointer.

why I use *(ptr+1) it prints the same value?

Because this will apply pointer arithmetics, which involve ptr, add 1 to it (by one here we mean the size of an int), and then use the * operator and refer to the content of this memory address (where it points) to, which is the same value as ptr[1].


arr[1] and &arr[1] might be pointing to the same location, but sematically they are different. arr[1] is equal to &arr[1][0] which is of type char*. &arr[1] is of type char (*)[10], as Some programmer dude said.

Upvotes: 0

haccks
haccks

Reputation: 106012

%s specifier in printf expects and argument of type char * (it should point to a null terminated string). ptr[1] is of char * type. So, no need to apply dereference operator here.

Upvotes: 1

Related Questions