Thread: pointer confusion

  1. #1
    Registered User
    Join Date
    Mar 2017
    Posts
    2

    pointer confusion

    Hey,

    I need a little help with pointers or maybe a good reference.

    I have this code:
    Code:
    char *foo(char* temp){
        return temp;
    }
    
    
    int main(int argc, char *argv[]){
    
    
        char *bar[4];
    
        bar[0] = foo("1");
        bar[1] = foo("2");
        bar[2] = foo("3");
        bar[3] = foo("4");
    
        printf("%s\n", bar[0]);
        printf("%s\n", bar[1]);
        printf("%s\n", bar[2]);
        printf("%s\n", bar[3]);
    
        return EXIT_SUCCESS;
    }
    the address of the temp variables is somewhere in the memory and could be overwritten right? As far as I know, the scope from temp ends on return and could be overwritten.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    You're not returning the address of the parameter, but it's value.

    Besides, this is also valid.
    Code:
    int foo ( ) {
      int answer = 42;
      return answer;
    }
    You're thinking of this, which is very wrong.
    Code:
    int *foo ( ) {
      int answer = 42;
      return &answer;  //!! wrong, address of a local.
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer confusion
    By rits in forum C Programming
    Replies: 3
    Last Post: 03-12-2009, 08:00 AM
  2. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  3. Pointer confusion
    By Blackroot in forum C++ Programming
    Replies: 11
    Last Post: 09-12-2007, 12:44 AM
  4. Pointer confusion...
    By fkheng in forum C Programming
    Replies: 13
    Last Post: 06-23-2003, 10:18 PM
  5. pointer confusion
    By badhri in forum C Programming
    Replies: 6
    Last Post: 05-07-2002, 06:08 AM

Tags for this Thread