1

Here is a program, I write it to output all the characters of a string one by one. But I also print the address of individual blocks of the array. The problem is addresses for all blocks are same. Why? Does someone know?

#include<stdio.h>
int main()
{
    char enter[]="Kinsman";
    char *ptr;  
    ptr=enter;
    int i=0;
    while(*ptr!='\0')
    {
        printf("%c%p\n",*ptr,&ptr);
        ptr++;
        for(i=0;i<=100000000;i++);
    }
return 0;
}
Ashish Tomer
  • 55
  • 1
  • 8
  • 5
    `for(i=0;i<=100000000;i++);` ?? why this – Grijesh Chauhan Oct 30 '13 at 10:50
  • 1
    @GrijeshChauhan Back on my old ATARI 800XL, waiting one second was accomplished easily with `FOR I=1 TO 500: NEXT I`. But this method - waiting in terms of cycles - has been outdated for about 20 years. – glglgl Oct 30 '13 at 11:17
  • @glglgl Yes I read it somewhere in past and it will consume CPU cycles. ~~ But a C compiler can optimize it by replacing `i = 100000000;`.. it is not reliable. Correct? – Grijesh Chauhan Oct 30 '13 at 11:22
  • @GrijeshChauhan I used it just to give a pause for each output through loop. – Ashish Tomer Oct 30 '13 at 11:28
  • @glglgl From your comments it looks like you both are professionals. – Ashish Tomer Oct 30 '13 at 11:29
  • 1
    @AshishTomer It is better to use the appropriate function - `sleep()` or `usleep()` on Unix, `Sleep()` on WIndows. – glglgl Oct 30 '13 at 11:36
  • @GrijeshChauhan This is right. Most modern compilers will probably optimize it away; forgot about that. – glglgl Oct 30 '13 at 11:37
  • @glglgl: Or if you can use C11, [thrd_sleep](http://en.cppreference.com/w/c/thread/thrd_sleep) would be a cross-platform solution. – legends2k Oct 30 '13 at 12:14

3 Answers3

4

Because you print the address of the actual pointer.

When you use &ptr you get the address of the actual pointer and not the address if points to. Remove the ampersand (address-of operator &) so you have only ptr.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

You are printing the address of the pointer, not the value of the pointer

Try

printf("%c%p\n",*ptr, static_cast<void*>(ptr));

(https://stackoverflow.com/a/18929285/259)

Community
  • 1
  • 1
David Sykes
  • 48,469
  • 17
  • 71
  • 80
1

ptr is a pointer and it is also a variable in stack that has an address. This is fixed, while what it points to is varying by ptr++, thus you've to print the pointed-to value and not the address of the pointer itself.

 printf("%c%p\n",*ptr, (void*)ptr);
 //                   ^  remove & , and add void*
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • Can you tell me how do I clear screen?
    I added conio.h but GCC gives error: "reverse.c:2:18: fatal error: conio.h: **No such file or directory** #include ^ compilation terminated."
    – Ashish Tomer Oct 30 '13 at 11:04