Thread: confusing about pointer..

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    36

    confusing about pointer..

    This program works properly but i got bit confused on some point...
    Code:
    #include <stdio.h>
       #include <stdlib.h>
       #define MAXSTRING 100
    
       int main(void) {
    
       char c ='a', *p, s[MAXSTRING];
       p = &c;
       printf("%c%c%c%c  ", *p, *p + 1, *p+2);
       strcpy(s, "ABC");
       printf("%s  %c%c %c\n", s, *s+6, *s+7, s+1);
       strcpy(s, "she sells sea shells by the seashore");
       p = s + 14;
       for (; *p != '\0'; ++p) {
       if ( *p == 'e')
         *p = 'E';
       if ( *p == ' ')
        *p = '\n';
     }
      printf("%s\n", s);
     return 0;
    }
    The output will be
    abc ABC GHBC
    .....
    ...
    ..
    And if i made some changes on the char s that i remove the pointer
    Code:
       strcpy(s, "ABC");
       printf("%s  %c%c%s\n", s,  s+6,  s+7,  s+1);
    the output will be
    ABC FGBC

    here's the problem..it looks like the start counting with 1..issit true..n didn't it suppose to be same answer as above?I will appreciate everuthing if u guys help me...thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    char c ='a', *p, s[MAXSTRING];
       p = &c;
    Your program shouldn't work at all. You're just lucky it does. You've made your pointer point to a single character, and then you run off past the end of it into some place you don't belong. You're very lucky your program doesn't crash.

    There's no reason it should work at all. Again, pure luck.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Code:
       strcpy(s, "ABC");
       printf("%s  %c%c%s\n", s,  s+6,  s+7,  s+1);
    Your code above attempts to access the "garbage" after when the string "ABC" ends.s + 6 means to use pointer arithmetic and access 6 addresses after s which is undefined, same with s + 7.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    36
    oo..ok..Thanks anyway...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting with pointer of pointers to array
    By dunpealslyr in forum C++ Programming
    Replies: 6
    Last Post: 10-01-2007, 11:26 PM
  2. confusing char pointer
    By vaibhav in forum C Programming
    Replies: 7
    Last Post: 08-29-2005, 07:45 PM
  3. Pointer To Functions In COM Confusing
    By bartybasher in forum C++ Programming
    Replies: 4
    Last Post: 08-05-2004, 03:08 PM
  4. Another Linked List plee
    By Dragoncaster131 in forum C Programming
    Replies: 3
    Last Post: 05-15-2004, 05:40 PM
  5. Replies: 2
    Last Post: 11-22-2001, 12:22 PM