1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Char pointer function output

  1. Sep 18, 2016 #1
    1. The problem statement, all variables and given/known data
    This is the code on Turbo C++
    Code (C):

    char * disp()
    {  
           int a [ ] = {49,15,50,34} ;
           char c [ ] ="1234" ;
           for (int i= 0; i<3 ; i++)
             c[i] =a[i] + c[i];
           cout<<c;
           return c;
    }

    void main()
    {
          clrscr();
          cout<<" ,"<<disp()<<endl;
          getch();
    }

     
    What will be the output for this:
    1. bAe4, undefined
    2. bAe4, bAe4

    2. Relevant equations


    3. The attempt at a solution
    I ran the program on turbo c++ and it was giving me the 1st option as output (undefined here I guess means random symbols like smilies which were appearing on my screen).
    I thought it should be the 2nd one.
    I know how we are getting bAe4 which is related to ASCII manipulation.
    The thing is that when we are returning the c, it would be holding the same characters.
    So, in the cout statement of main(), we should get bAe4 once again.
    Why is that not true?
     
    Last edited by a moderator: Sep 18, 2016
  2. jcsd
  3. Sep 18, 2016 #2

    Mark44

    Staff: Mentor

    The array named c is a local variable in your disp() function. The scope of c is only within disp(), so the call to cout within disp() works as expected, but c ceases to exist after the return from disp(). In Visual Studio, which I'm running, the compiler resets the memory that the c array was using after the return from disp(), so the call to cout in main() results in uninitialized garbage.
     
    Last edited: Sep 18, 2016
  4. Sep 18, 2016 #3
    But why the output for this is 8 instead of garbage then, x also have scope to fact() only ?
    Code (C):

    #include<iostream.h>
    #include<conio.h>
    int fact()
    {
        int x=8;
        return x;
    }

    void main()
    {
       clrscr();
       cout<<fact();
       getch();
    }  
     
  5. Sep 18, 2016 #4

    Merlin3189

    User Avatar
    Gold Member

    Perhaps because it is an integer value which is returned on the stack. The storage for x is reset, but the value is on the stack.
    In your first example the returned value is a pointer to an array which no longer exists. You get a pointer on the stack, but where it points is no longer valid.
     
  6. Sep 18, 2016 #5

    Mark44

    Staff: Mentor

    In the earlier example of this thread, your disp() function returned an address, so the actual value returned was correct, but this was the address of a local variable, and the memory at that address was reinitialized just after the disp() function returned. This caused garbage to be displayed in main().
    Since the value being returned is an int, it's more likely that it is being returned in a register, especially if the machine is one with an x86 architecture.
     
  7. Sep 18, 2016 #6
    So the return is useful for int, double and other data types except char in this type of architecture?
    Edit: It works for char also, also char* but not char[ ]
     
  8. Sep 18, 2016 #7

    Mark44

    Staff: Mentor

    Right (including your edit comment). You can return a scalar (i.e, char, short, int, long, float, double, etc), but if you return a pointer, the contents of the memory at that location will be garbage if what is pointed to is of local scope.
     
  9. Sep 18, 2016 #8
    Ok but it is correct I think in case of int pointer. Only char pointers have problem?
    Also after a scope ends, memory is reinitialized and since pointer points to memory its contents gets changed but in case of returning a scalar what is happening?
    Why scalar memory also not changes and therefore its value?
     
  10. Sep 18, 2016 #9

    Mark44

    Staff: Mentor

    No, it doesn't really have to do with the type of data that is pointed to, but it does seem to be that char arrays get reinitialized when they go out of scope, and other arrays don't have this happen (based on my installation of Visual Studio). Nevertheless, it's a bad idea to return a pointer to a local variable of a function. There's no guarantee that what's at that address won't have changed.
    Whatever you return gets copied somewhere, likely to one of the CPU registers. If you return a pointer to some type, that address gets copied with no problem, but what's at the address may or may not be valid if the thing pointed to is a local variable that's now out of scope.
     
  11. Sep 19, 2016 #10

    NascentOxygen

    User Avatar

    Staff: Mentor

    So if this statement char c [ ] ="1234" ; were moved into main() then the program should execute as hoped?
     
  12. Sep 19, 2016 #11

    Mark44

    Staff: Mentor

    No.
    Here's the change you described:
    Code (C):
    char * disp()
    {
           int a [ ] = {49,15,50,34} ;
         
           for (int i= 0; i<3 ; i++)
             c[i] =a[i] + c[i];
           cout<<c;
           return c;
    }

    void main()
    {
          clrscr();
          char c [ ] ="1234" ;
           cout<<" ,"<<disp()<<endl;
          getch();
    }
    The code above won't compile, as the identifier c isn't known to or accessible by the disp() function. Here the scope of the identifier c is just main().

    You could get around this by declaring c outside of all functions, making it a global variable, like so:

    Code (C):

    char * disp();   // Declaration of disp() function
    char c [ ] ="1234" ;  // Array c is now global, accessible by both main() and disp()

    int main()
    {
        cout<<" ,"<<disp()<<endl;
        return 0;
    }

    char * disp()
    {
       int a [ ] = {49,15,50,34} ;
         
       for (int i= 0; i<3 ; i++)
             c[i] =a[i] + c[i];
       cout<<c;
       return c;
    }
    Note that I have modified the original code somewhat, by moving main() to the top (my preference), and removing some nonessential lines of code. Also, this isn't complete code, as it doesn't either include the necessary header files or have the proper using statement.
    This workaround is not an ideal solution, as global variables are discouraged, for the most part.

    Here is a better solution, and one that is a complete, working program.
    Code (C):

    using std::cout;
    using std::endl;

    char * disp(char *);   // Declaration of disp() function
     
    int main()
    {
        char c [ ] ="1234" ;
        cout << " ," << disp() << endl;
        return 0;
    }

    char * disp(char * c)
    {
       char a [ ] = {49, 15, 50, 34} ;
         
       for (int i = 0; i < 3 ; i++)   // Note that only c[0], c[1], and c[2] are modified
             c[i] = a[i] + c[i];
       cout << c;
       return c;
    }
    Output is bAe4 , bAe4, same as 2nd answer in the original post.
     
  13. Oct 7, 2016 #12
    In linked list we usually do that -returning head node.
    Eg:
    Linkedlist * Linkedlist::del (int val, Linkedlist* head){
    ........
    .......
    return head;}
    Here head does not get reinitialized.
    Is it only the problem with char arrays?
     
  14. Oct 7, 2016 #13

    Mark44

    Staff: Mentor

     
  15. Oct 7, 2016 #14
    So, it depends on the type of software which you have and compilers? As apart from visual studio this also happens on turbo c++
     
  16. Oct 7, 2016 #15

    Mark44

    Staff: Mentor

    It is probably implementation-dependent. As far as I know, there is nothing in how the language is defined that causes this to happen.
     
  17. Oct 7, 2016 #16
    So in general, we should not return pointers by the definition of language. It was only chance or implementation dependent that I was getting correct value for integer arrays?
     
  18. Oct 7, 2016 #17

    Mark44

    Staff: Mentor

    It has nothing to do with how the language is defined. If a variable is defined inside a function, it is local to that function. The function should not return a pointer to that variable, because there's no guarantee that the memory being pointed to won't get re-used for some other purpose (hence, have its value changed).


    That's what I think.
     
  19. Oct 7, 2016 #18
    Thanks for solving queries.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Char pointer function output
Loading...