Barton Yon
Barton Yon

Reputation: 13

How does pointers of array work in the question?

This is an question on my textbook.

char array[26];
char *cptr = array;
char c;
for(c = 'A'; c<('A'+26);c++)
{
    *cptr ++=c ;
    printf("%d %c %d\n",cptr,c,c);
}

I want to know why the variety cptr in this line printf("%d %c %d\n",cptr,c,c); could print like

6487537 A 65
6487538 B 66
6487539 C 67
6487540 D 68
6487541 E 69
6487542 F 70
6487543 G 71
6487544 H 72
6487545 I 73

and not like constant

6487536 A 65
6487536 B 66
6487536 C 67
6487536 D 68
6487536 E 69
6487536 F 70
6487536 G 71
6487536 H 72
6487536 I 73

Upvotes: 1

Views: 59

Answers (2)

bruno
bruno

Reputation: 32586

char *cptr = array;

initialize cptr to point to the first entry of array

 *cptr ++=c ;

is equivalent of

*cptr=c;
cptr += 1; /* or "cptr++;" or "++cptr;" as you prefer */

so set the element pointed by cptr to the value of c, then modify cptr to point to the next element

so populate array with A then B etc

printf("%d %c %d\n",cptr,c,c);

prints (wrongly because the right format is %p) the cptr then c as a character then the character code, so print the address of each element of the array + 1

You will have the same prints doing :

printf("%d %c %d\n",cptr,cptr[-1], cptr[-1]);

even again to print the address the right format is not %d but %p, so

printf("%p %c %d\n",cptr,cptr[-1], cptr[-1]);

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222754

The spaces in *cptr ++=c ; may be misleading. Better spacing would be *cptr++ = c;. The precedence of the operators causes this to be grouped as *(cptr++) = c;. This means:

  • cptr++ says to increment cptr by 1. However, the value used in this expression will be the value before the increment.
  • *cptr++ says to use the pointed-to location. This will be the location where cptr pointed to before the increment.
  • *cptr++ = c; puts the value of c in the pointed-to location.

Also note you should not print a pointer with %d. To print a pointer, convert it to void * and print using %p: printf("%p %c %d\n", (void *) cptr, c, c);.

Upvotes: 2

Related Questions