Thread: pass by refrence help.

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    13

    pass by refrence help.

    The function takes a string pointer and returns by refrence a string . I can print the string just fine in the function inself but when i try to print it from the main function it prints some junk. Can any body tell me why?? Pleaseeeeeeeeeeeeeeeeeeeeeeeeeeeeee

    Code:
    int validateInptFile(char *fPtr, char **seqNo){
    char fileName[18], sNo[10];
    
    strncpy(sNo, &fileName[9], 4);
    sNo[4] = '\0';
    
    *seqNo = &sNo[0];
    printf("seqNo > %s\n", *seqNo);
    //output "0001"
    }
    
    
    //function call from main
    
    validateInptFile(newAddFile, &curSeqNo));
    printf("MAIN > %s\n", curSeqNo);
    //outputs some junk

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    1) References don't exist in C. You are using a pointer to get to the data
    2) You are trying to use a pointer to a local nonstatic variable that is destroyed after the function end

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Simpler is:
    Code:
    int validateInptFile(char *fPtr, char *seqNo){
       char fileName[18], sNo[10];
    
       strncpy(sNo, &fileName[9], 4);
       sNo[4] = '\0';
    
       strcpy(seqNo, sNo);
       printf("seqNo > %s\n", seqNo);
       //output "0001"
    }
    Or even simpler:
    Code:
    int validateInptFile(char *fPtr, char *seqNo){
       char fileName[18];
    
       strncpy(seqNo, &fileName[9], 4);
       seqNo[4] = '\0';
    
       printf("seqNo > %s\n", seqNo);
       //output "0001"
    }
    And then the call would be:
    Code:
    validateInptFile(newAddFile, curSeqNo));

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Speed test result
    By audinue in forum C Programming
    Replies: 4
    Last Post: 07-07-2008, 05:18 AM
  2. Replies: 3
    Last Post: 11-22-2007, 12:58 AM
  3. map pass by refrence?
    By curlious in forum C++ Programming
    Replies: 2
    Last Post: 09-28-2003, 10:11 AM
  4. pass be reference versus pass by value
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 08-01-2002, 01:03 PM
  5. Replies: 3
    Last Post: 04-02-2002, 01:39 PM