Exforsys
+ Reply to Thread
Results 1 to 2 of 2

Different Output

This is a discussion on Different Output within the C and C++ forums, part of the Programming Talk category; I write the following C program and a ran the program #include <stdio.h> int * test(int, int); void main() { ...

  1. #1
    ashlee is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    108

    Exclamation Different Output

    I write the following C program and a ran the program

    #include <stdio.h>
    int * test(int, int);
    void main()
    {
    int *ex = test(10,20);
    printf("\nSample Testing\n");
    printf("&#37;d",*ex);
    }
    int *test(int a,int b)
    {
    int c = a + b;
    return &c;
    }

    In the above program I thought the output would be
    Sample Testing
    30

    But I got output as
    Sample Testing
    some junk value

    Why is it so? I am confused on the output the system shows. Someone highlight me your knowledge on this.


  2. #2
    Adrian is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    124
    It is because the function test(10,20) is passed by value and you have calculated c = a + b which is fine. But you have returned the address of c which is collected in a pointer. It is possible to change the address value and so you have got a junk value. For retrieving the value you can even pass by reference and get the return value in the function name itself.


Latest Article

Network Security Risk Assessment and Measurement

Read More...