LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices



Reply
 
Search this Thread
Old 08-05-2003, 02:08 PM   #1
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Rep: Reputation: 30
Returning an object


Is it possible to return an object (which is newed in the function) as the function return value? Or for instance an array of int?
Code:
int* MyFunc () {
  int* k = new int[10];
  return k;
}
or
Code:
int* MyFunc () {
  int RetVal[3] = {1, 2, 3}
  retrun RetVal;
}
As the rule of automatic variables, in the last code the memory allocated for the array (of int) should be freeed (spl?) before the end of function's block, so the values could not be retrieved somewhere by assigning function tio an array, for example:
Code:
main() {
  int a[10] = MyFunc();
}
 
Old 08-05-2003, 02:27 PM   #2
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 50
Code listing 1 is perfectly fine, just remember to delete anything you new.

The second code listing as you say retval will be deallocated off the stack before MyFunc() returns and thus a 'wild' pointer will be returned. the 3rd code listing doesnt make sense you cant assign to an array like that i think what you meant was
Code:
main() {
    int *a = MyFunc();
}
 
Old 08-05-2003, 11:59 PM   #3
magicvash
Member
 
Registered: Aug 2003
Location: Chicago
Distribution: Mandrake 9.1 (x86)
Posts: 62

Rep: Reputation: 15
Re: Returning an object

Quote:
Originally posted by Mohsen

Code:
int* MyFunc () {
  int* k = new int[10];
  return k;
}
To use this, do exactly as you said.

Code:
int main() {

  int* myarray = MyFunc();
  // code continues...
  // ...
 delete [] myarray;
 return 0;
}

Last edited by magicvash; 08-06-2003 at 12:00 AM.
 
Old 08-06-2003, 12:11 AM   #4
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Original Poster
Rep: Reputation: 30
Thanks.
1. Is there the same case in C?
2. Is it explicit to compiler to determine the size of an array of something except char* returned from (passed to) a function? e.g.
Code:
int myfunc (int* k) {
  //...
}
main () {
  int k = 10;
  int v[] = {1, 2, 3};

  myfunc (&k); /*How does it determine that an array or a pointer to int is pased?*/
  myfunc (v);
}
 
Old 08-06-2003, 12:53 AM   #5
magicvash
Member
 
Registered: Aug 2003
Location: Chicago
Distribution: Mandrake 9.1 (x86)
Posts: 62

Rep: Reputation: 15
Quote:
1. Is there the same case in C?
What do you mean by that?

Quote:
2. Is it explicit to compiler to determine the size of an array of something except char* returned from (passed to) a function? e.g.
Code:
int myfunc (int* k) {
  //...
}
main () {
  int k = 10;
  int v[] = {1, 2, 3};

  myfunc (&k); /*How does it determine that an array or a pointer to int is pased?*/
  myfunc (v);
}
CS 101: pointer == array == pointer == array (etc..)
Essentially the variable you use to declare an array is a pointer to a an address that begins a contiguous block of memory. So if you declare an array of 10 int's, then on my system this is what will happen:

Code:
int v[] = {1,2,3}
This will cause 3*sizeof(int) bytes of contigious (i.e. all together) memory to be allocated and the address of the first byte is stored in v. so if you do:

Code:
printf("%d",v);
you should get the address of the first byte of the array 'v'

Another example of this is char* being used as a string. char* and char[] are almost the same (minus some memory management issues). so if i do

Code:
char v[3] = {'H',"i',0} // must have null char
char* w = "Hi";
printf("%s",v==w ? "yes" : "no);
I should get "yes" printed out since v is exactly the same as w

Hope that's what you're looking for
 
Old 08-06-2003, 08:48 AM   #6
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Original Poster
Rep: Reputation: 30
Thanks magicvash and kev82 for the help.

Quote:
Quote:
1. Is there the same case in C?
What do you mean by that?
1. I mean that for example we can return a structure from a function in ANSI C, and although this is (assume) an automatic variable, but can be retrieve from the scope out of function (from where it called). Why?


2. So we should always pass the size of array which is passed to a function.

ERROR :
Quote:
Code:
char v[3] = {'H',"i',0} // must have null char
char* w = "Hi";
printf("%s",v==w ? "yes" : "no);
I should get "yes" printed out since v is exactly the same as w
v==w?
I think that it wont give you yes because the address of the first character of character pointer v is not the same as character pointer w, isn't it. That's why we should use strcmp except.
 
Old 08-06-2003, 08:58 AM   #7
TheLinuxDuck
Member
 
Registered: Sep 2002
Location: Tulsa, OK
Distribution: Slack, baby!
Posts: 349

Rep: Reputation: 33
Mohsen:

Yes, you can do the same thing with C. You'd have to use malloc/calloc instead of new, though:
Code:
int* MyFunc () {
  int* k = malloc(sizeof(int) * 10);
  // k can be NULL or a valid memaddy at this point.
  return k;
}
main() {
  int *a = MyFunc();
}
Also, the v==w thing will print 'no', for the reason you stated.
 
Old 08-06-2003, 09:48 AM   #8
magicvash
Member
 
Registered: Aug 2003
Location: Chicago
Distribution: Mandrake 9.1 (x86)
Posts: 62

Rep: Reputation: 15
Quote:
v==w?
I think that it wont give you yes because the address of the first character of character pointer v is not the same as character pointer w, isn't it. That's why we should use strcmp except.
DURH
That's what I get for writing code at 2 am
 
Old 08-06-2003, 12:00 PM   #9
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Original Poster
Rep: Reputation: 30
TheLinuxDuck, I meant something like this: (in which an automatic variable is defined in the function block)
Code:
/* This is a C file */
struct S {
  int a, b;
};

struct S MyFunc () {
  struct S S_instance = {1, 2};
  /* ... */
  return S_instance;
}

main () {
  struct S S_ins;
  S_ins = MyFunc ();
}
When will the automatic variable S_instance free?
 
Old 08-06-2003, 01:35 PM   #10
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 50
well you learn something every day, i didnt think you could pass objects like that in c only in c++ but according to gcc you can.

what hapens depends on the compiler but basically
return s_instance; - takes a copy of s_instance
} - end of block, s_instance deallocated
s_ins = myfunc() - the copy of s_instance made by the return statement is copied into s_ins and the copy is deallocated
 
Old 08-07-2003, 12:24 AM   #11
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Original Poster
Rep: Reputation: 30
No, Ritchie explicitly mentioned that we can both get a parameter or return of a structure.
Quote:
Let us investigate structures by writing some functions to manipulate points and rectangles. There are at least three possible approaches: pass components separately, pass an entire structure, or pass a
an also here is an example by him:
Code:
/* makepoint: make a point from x and y components */
struct point makepoint(int x, int y)
{
  struct point temp;
  temp.x = x;
  temp.y = y;
  return temp;

}
 
Old 08-07-2003, 12:36 AM   #12
Mohsen
Member
 
Registered: Feb 2003
Location: Iran
Distribution: Solaris 10
Posts: 201

Original Poster
Rep: Reputation: 30
Something more
I have heard that there are some differences here between C and C++.
int C the automatic variable we be disposed as soon as the compiler reached to the next block (with the same depth), but in C++ the variable is disposed when its block finished.
here is an example:
Code:
//C++
class CPP{
public:
  int a, b;
};
CPP MyFunc () {
  CPP RetVal;
  /*...*/
  return RetVal; /* This -as I think- will be disposed at the 
                              next line */
}



// C code
struct C {
  int a, b;
};

struct C MyFunc1 () {
  struct C RetVal;
  /*...*/
  return RetVal;
}

int MyFunc2 () {}

main () {
  struct C* CPtr;
  CPtr = MyFunc1 ();
  MyFunc2 (); /* I think after this line, our pointer will be a 
                         wild one */
  return 0;
}
I tried hard to find something in Ritchie's or Stroustrap's book but I can't.
 
Old 08-07-2003, 03:41 AM   #13
chens_83
Member
 
Registered: Dec 2001
Location: Adelaide , South Australia
Distribution: redhat 7.2, Debian , OpenBSD
Posts: 123

Rep: Reputation: 15
Well , once a function has gone out of scope, the local variables are destroyed. (So to speak) . The variables that you allocate will remain constant in the heap until the program is killed. The wild pointer that you speak of wont be wild, because it is not on the heap, (no new , or malloc has been called) Remember a pointer is just like a int (4 byte) and they also go out of scope (destroyed) once the function has exited.

If you want to check out what is happening try using a debugger and watch your variables disappear once they are out of scope.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

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 Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
compile error while returning STL iterator as object * rameshmiraje Programming 2 06-20-2004 02:50 PM
Returning to X from terminal RemusX2 Linux - General 2 06-05-2004 05:30 PM
Event driven object-to-object: C++ template class mecanism ( NOT STL or STDC++) bretzeltux Programming 2 12-23-2003 03:45 PM
returning a reference to Object C++ chens_83 Programming 3 10-10-2003 10:16 PM
returning static guest72485 Programming 3 08-26-2002 01:50 AM


All times are GMT -5. The time now is 11:33 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration