Thread: C beginning, transfer value by pointer

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    90

    C beginning, transfer value by pointer

    Hello,
    I would like to clear some things regarding transfer a value by pointer among porcedures in project.

    Situation:
    In header I have declaration of function prototype:
    Code:
        char* getstatus(int bd);
    Function, in separate file look's like this:
    Code:
    char* getstatus(int bd)
    {
        char temp[10] = "54321ACFEB";
        return = &temp[bd];
    }
    Main file:
    Code:
    char* gs; 
    gs = getstatus(5);
    printf(" %s\n", gs);
    
    if (gs == "A")
        printf("gs is %s\n", gs);
    This of course don't work.
    And this works but still don't good enough:
    Code:
    char* getstatus(int bd)
    {
        char* k;
        char temp[10] = "54321ACFEB";
        char f[2] = {0};
        strncpy(k, &temp[bd], 1);
        k = &temp[bd];
        return k;
    }
    How to transfer a char* from function in another module to main module reliably so condition if (gs == "A") will work and how to write that code shortly as possible?

    If I strcpy gs to chararray in main file then all this work OK but I think that I do something more than is actually needed and something less to have propper code.

  2. #2
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    In the examples you've shown, the variables in getstatus() are on the stack and go out of scope when getstatus() returns. You could have getstatus() allocate memory (malloc()) which would then get memory from the heap, but then the program calling getstatus() would eventually have to free the memory allocated by getstatus(). You could use a global or static variable, but that would not be "re-entrant" compatible (an issue if the function calling getstatus() also calls itself, or if the program using getstatus() was multi-threaded.

    You could have getstatus() return a char * relative to a char * passed to getstatus() as a parameter:

    Code:
    char * getstatus(char *pchr, int bd)
    {
    /* ... */
        return(pchr+bd);
    }

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Why are you trying to return a pointer?

    Why not just return the character?
    Code:
    char getstatus(int bd)
    {
        char temp[10] = "54321ACFEB";
        if(bd < 10)
           return temp[bd];
        else
           // Return something indicating failure.
    }
    // main code:
    
    char gs;
    gs = getstatus(5);
    printf(" %c\n", gs);
     
    if (gs == 'A')
        printf("gs is %c\n", gs);
    Jim

  4. #4
    Registered User
    Join Date
    Mar 2010
    Posts
    90
    @jimblumberg, this don't work.
    @rcgldr

    I see about that problems.
    As for now I can get data to main program like this:
    Code:
            char f[2] = {0};
            strcpy(f, getstatus(5));
            printf(" %s\n", f);
            if (f == "A")
            {
                printf("gs is %s\n", f);
            }
    But I just search for more elegant way if exists.
    However, in this case I havent to free anything after getting data.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    You cannot compare character strings using == in C; you would need to use the strcmp function. You can however compare straight chars as suggested in the post #3.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Mar 2010
    Posts
    90
    @hk_mp5kpdw

    Like that?
    Code:
            strcpy(f, getstatus(sel));
            if (f[0] == '0' || f[0] == ' ' || f[0] == '\0')

  7. #7
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by nime View Post
    @jimblumberg, this don't work.
    Why doesn't Jim's solution work?

    Bye, Andreas

  8. #8
    Registered User
    Join Date
    Mar 2010
    Posts
    90
    Andi, because I have concrete situation behind this simplified example which requires to pass a pointer.

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    The why don't you show us this "concrete" situation?

    Jim

  10. #10
    Registered User
    Join Date
    Mar 2010
    Posts
    90
    Because it is part of complex project what mean not suitable to post here as example.

  11. #11
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    If I'm getting this right, you want getstatus(int bd) to return the sub-string of temp[] that starts at position bd. If so, then you need to pass temp as an argument to the function too.

    But something like that would be a bit silly, because if temp is defined in the caller's context then you could directly use &temp[bd]...

    Code:
    int main( void )
    {
       char temp[10] = "54321ACFEB", *gs = &temp[5];
       ...

  12. #12
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by nime View Post
    Because it is part of complex project what mean not suitable to post here as example.
    But then you need to understand that we can't help you if you don't tell us what the real problem is you are trying to solve.
    See also "Describe the goal, not the step"

    Bye, Andreas
    Last edited by AndiPersti; 05-30-2013 at 01:48 AM. Reason: link added

  13. #13
    Registered User
    Join Date
    Mar 2010
    Posts
    90
    @Andi, I already get satisfied answer in first two replies to my question what mean that question is formed correctly.

    I practic situation my char array (temp) is readen from binary file and behind it is defined data structure with various datatypes so I have to post much of non relevant code which involve gui stuff, database stuff, charactersets conversion stuff and other...
    If you want to see a goal you don't have to see whole match.

    @migf1, no, temp is not known in the caller. So whe have to go to getstatus to get an important part of temp (one char in this case).

  14. #14
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    Before anything else, please note that in your example, if temp is to be used as a cstring you should define it with room for 11 chars: those 10 you initialize it with + 1 for the terminating '\0'.

    If you intend to use it as a plain char array, consider defining it explicitly...

    Code:
    char temp[10] = {
        '5', '4', '3', '2', '1', 'A', 'C', 'F', 'E', 'B'
    };
    and refrain from passing it to functions that expect cstrings (that is, all standard C string functions).

    Quote Originally Posted by nime View Post
    @Andi, I already get satisfied answer in first two replies to my question what mean that question is formed correctly.

    I practic situation my char array (temp) is readen from binary file and behind it is defined data structure with various datatypes so I have to post much of non relevant code which involve gui stuff, database stuff, charactersets conversion stuff and other...
    If you want to see a goal you don't have to see whole match.

    @migf1, no, temp is not known in the caller. So whe have to go to getstatus to get an important part of temp (one char in this case).
    So I guess, getstatus() generates locally a cstring temp and you need to save in caller's context some part of temp starting at bd, right?

    If so, then the solution given in post #2 doesn't seem suitable, since it assumes that temp is known to the caller, who passes it to the function.

    Now, if you only need to return to the caller the bd-th character of temp, then there is no need for the function to return a char pointer, and the solution given in post #3 should be sufficient.

    On the other hand, if you need to return to the caller the substring of temp that starts at position bd (which would make more sense, given the signature of getstatus()) you should allocate room for the substring inside the function, copy &temp[bd] into it and return it. In this case, you should free() the returned substring in caller's context, when done using it.

    Here's a possible implementation, assuming temp is a plain char array and not a cstring...

    Code:
    char *getstatus( int bd )
    {
        char *ret = NULL;
        char temp[10] = { '5', '4', '3', '2', '1', 'A', 'C', 'F', 'E', 'B' };
        size_t sz = 10 - bd;
    
        if ( sz < 1 || sz > 10 )
            return NULL;
    
        ret = malloc( sz /* * sizeof(char) */ );
        if ( !ret )
            return NULL;
    
        memcpy( ret, &temp[bd], sz);
        return ret;
    }
    Then in the caller...

    Code:
    int main( void )
    {
        char *gs = getstatus(5);
    
        if ( !gs ) {
            /* getstatus() failed, handle error here */
        }
        else {
            /* do whatever you need to do with gs here, then... */
            free( gs );
            gs = NULL;
        }
        ...

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by migf1
    If you intend to use it as a plain char array, consider defining it explicitly...
    Code:
    char temp[10] = {
        '5', '4', '3', '2', '1', 'A', 'C', 'F', 'E', 'B'
    };
    Unless you intend it to be compilable as C++, you could still use a string literal for initialisation, but then there should be a comment to clearly state that.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File Transfer Using UDP/IP
    By AdamOhio76 in forum Networking/Device Communication
    Replies: 6
    Last Post: 03-19-2011, 02:37 PM
  2. Transfer function in C ? How to do it ?
    By integralx2 in forum C Programming
    Replies: 2
    Last Post: 01-09-2011, 08:49 PM
  3. transfer
    By C-Compiler in forum Windows Programming
    Replies: 6
    Last Post: 11-23-2008, 08:07 PM
  4. File Transfer
    By rogue in forum C++ Programming
    Replies: 6
    Last Post: 01-25-2006, 07:57 AM
  5. Replies: 5
    Last Post: 06-03-2002, 08:47 AM