Thread: Playing with pointers

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    29

    Playing with pointers

    Consider this:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int c;
        char *argv[] = {"hello", "world"};
    
        printf("%s\n", argv[1]);
    
        while (c = *(argv[1])++)
            putchar(c);
    
        return 0;
    }
    Is there another way to access the word "world"?

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    argv[1] is equivalent to *(argv + 1), but since they're the same thing just expressed differently, I don't know that I'd call that another way.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You could declare a pointer to argv and access it that way.

    Is this allowed?
    Code:
    while (c = *(argv[1])++)
    I'm pretty sure it's C99, but what about C89? I thought you had to go
    Code:
    while ((c = *(argv[1])++))
    in C89.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    dwks, why do you think C89 requires a redundant pair of parentheses there?

    gcc with -Wall (and probably other compilers) will suggest an extra pair because it thinks you might have made a mistake, and meant ==. It can't tell that you know what you're doing and really want to assign a value to c and test the result instead of wanting to compare.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers to constants and constant pointers
    By homeyg in forum C++ Programming
    Replies: 1
    Last Post: 06-18-2005, 12:02 AM
  2. Arrays, pointers and strings
    By Apropos in forum C++ Programming
    Replies: 12
    Last Post: 03-21-2005, 11:25 PM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Array of pointers
    By falconetti in forum C Programming
    Replies: 5
    Last Post: 01-11-2002, 07:26 PM