Exforsys

Online Training

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); ...


Go Back   Exforsys > Programming Talk > C and C++

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 05-10-2007, 03:59 PM
Senior Member
 
Join Date: Apr 2006
Posts: 125
ashlee is on a distinguished road
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("%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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 05-13-2007, 10:39 AM
Senior Member
 
Join Date: Apr 2006
Posts: 141
Adrian is on a distinguished road
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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads

Thread Thread Starter Forum Replies Last Post
Output of the Statement Adrian Oracle Database 2 04-26-2008 04:40 AM
To get Output Rahulbatra C and C++ 1 05-10-2007 09:23 AM
To achieve Output Ralph Linux 0 12-12-2006 03:58 AM
C Programming - Managing Input and Output Operations JobHelper Career Advice 0 04-15-2006 08:30 AM
[gnu.bash.bug] BASH Frequently-Asked Questions (FAQ version 3.26) Chet Ramey Tech FAQ 0 04-26-2004 11:00 AM


All times are GMT -4. The time now is 12:16 AM.


Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.1.0
Copyright 2004 - 2007 Exforsys Inc. All rights reserved.