GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 12-Sep-2008, 10:09
zalezog zalezog is offline
Junior Member
 
Join Date: Oct 2007
Posts: 33
zalezog will become famous soon enough
Unhappy

How to retrieve arrays from functions?


i get a an unusual no: by executing the following code.By execution it seems to me that by performing a return statement,the function re-executes itself.Can anyone explain that and the proper way to do it?
Thanks.
CPP / C++ / C Code:
#include<iostream>
#include<stdlib.h>
float getdata(float[],int count=10);

using namespace std;
int main()
{
int count;
float input[count];
cout<<"How many numbers";
cin>>count;
for(int i=0;i<count;i++)
     cin>>input[i];
getdata(input,count);
cout<<getdata(input,count);

system("pause");
return 0;
}
float getdata(float input[],int count)
{
  cout<<"\n am inside the func";
  for(int i=0;i<count;i++)
     cout<<input[i]<<endl;   
return(input[count]);
}

  #2  
Old 12-Sep-2008, 10:37
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: How to retrieve arrays from functions?


Quote:
Originally Posted by zalezog
CPP / C++ / C Code:
int count;
float input[count];
Since count has never been initialized, the array created will be of undetermined size. The amount of space allocated to arrays is defined at compilation time, not runtime.
Quote:
CPP / C++ / C Code:
cout<<"How many numbers";
cin>>count;
for(int i=0;i<count;i++)
     cin>>input[i];
The array has already been created before count has been initialized. If the value assigned to count at runtime is larger than the array created, then values will be written into unallocated space. This can potentially have dire consequences.
Quote:
...it seems to me that by performing a return statement,the function re-executes itself.
Close.

If the value of count is larger than the size of the array, then depending upon the platform, the return address placed on the stack may be corrupted because it is being overwritten. This would account for why you are seeing execution go into the weeds upon executing the function.
  #3  
Old 12-Sep-2008, 12:29
zalezog zalezog is offline
Junior Member
 
Join Date: Oct 2007
Posts: 33
zalezog will become famous soon enough
Lightbulb

Re: How to retrieve arrays from functions?


Are you saying that the array i have created is not a dynamic one but a static array of a size unknown to me which may be larger or smaller than
CPP / C++ / C Code:
count
?If that is the case what is that unusual number that pops after execution?What should be the correct syntax or the altered way of retrieving an array from a function?

Quote:
This can potentially have dire consequences.
I don't understand this .What do you mean by"dire consequences"?
  #4  
Old 12-Sep-2008, 13:35
dlp dlp is offline
Member
 
Join Date: May 2006
Posts: 157
dlp has a spectacular aura about

Re: How to retrieve arrays from functions?


Regarding dire consequences, think of it this way:

You make an array of size 100 of ints.

CPP / C++ / C Code:
int thearray[100];

The thing is, basically this is a chunk of memory that is the size of 100 ints. Now, do you know what comes after this chunk of memory? What piece of memory exists directly after the array? Nope. Neither do we. That's where the dire consequences are. Should you do something such as write at right after the point where that chunk of memory ends, you could be over writing something other variable that's critical to some other part of your program, or worse another program. Imagine you have your program running, and attempt to print the value of an int only to find garbage because another program overwrote it.

Unrealistic real life simile: Imagine you're driving your car. Your car contains many mechanical pieces. Now imagine, for some reason, someone elses car is made and because of the way it's made, it suddenly causes your tire to pop while you drive at 60 miles per hour or become a smaller tire than you currently have on which just screws with the handling. Think of your programs like cars driving through your computer, and one just screws up the others tires. That's the dire consequence of not using an array properly (or at least the way I see it).
  #5  
Old 12-Sep-2008, 13:36
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: How to retrieve arrays from functions?


Quote:
Originally Posted by zalezog
Are you saying that the array i have created is not a dynamic one but a static array of a size unknown to me which may be larger or smaller than
CPP / C++ / C Code:
count
?
Yes. Arrays dynamically sized at runtime can only be created through operator new() or functions like malloc().
Quote:
If that is the case what is that unusual number that pops after execution?
Neither do I know the number you are referring to nor is it important. You are defining an array without initializing its contents, so the values of each element will only be whatever was the contents of memory at the time of execution.
Quote:
What should be the correct syntax or the altered way of retrieving an array from a function?
Most important is realizing that the array has a predefined size, & ensuring that writes are not done outside these boundaries. Nothing was wrong with the function as originally defined, however, consider the following:
CPP / C++ / C Code:
#include <iostream>

using namespace std;

void echo(float[], int);

int
main() {
    const int size = 4;
    float a[size];
    int n;

    do {
        cout << "enter size:" << endl;
        cin >> n;
    } while (n <= 0 || n > size);  // ensure #elements fit within the array

    for (int i = 0; i < n; ++i) {
        cout << i << ":" << endl;
        cin >> a[i];
    }

    echo(a, n);

    return 0;
}

void
echo(float a[], int k) {
    for (int i = 0; i < k; ++i)
        cout << i << ":\t" << a[i] << endl;;
}
The only significant difference in this example is that the number of elements written into the array is constrained by the predefined array size.
Quote:
I don't understand this .What do you mean by"dire consequences"?
When a function is called, the address where execution should resume after the function has finished is placed on the stack. Given that you have potentially overwritten this address, execution will not resume where intended, but wherever the overwritten address specifies. The processor will attempt to interpret whatever is at this location as valid instructions, but given that all binary values are not valid instructions, the processor will either fault due to an illegal instruction or generate a segmentation error due to an attempt to access an illegal address.
Last edited by ocicat : 12-Sep-2008 at 14:12.
  #6  
Old 13-Sep-2008, 00:59
zalezog zalezog is offline
Junior Member
 
Join Date: Oct 2007
Posts: 33
zalezog will become famous soon enough
Question

Re: How to retrieve arrays from functions?


Ok ,my mistake was that i was trying to overwrite into a memory location that is not even assigned to
CPP / C++ / C Code:
thearray[]

But Ocicat ,the function
CPP / C++ / C Code:
void echo(float[], int);
does not return any value its return type is
CPP / C++ / C Code:
 void
.But in my original program,I want the same function to return the whole array to my
CPP / C++ / C Code:
main()
.Then i want my program to again display the contents of the array.I tried doing that
by slightly altering your program like this::
CPP / C++ / C Code:
#include <iostream>
#include<process.h>
using namespace std;

float echo(float[], int);

int
main() {
    const int size = 4;
    float a[size];
    int n;

    do {
        cout << "enter size:" << endl;
        cin >> n;
    } while (n <= 0 || n > size);  // ensure #elements fit within the array

    for (int i = 0; i < n; ++i) {
        cout << i << ":" << endl;
        cin >> a[i];
    }

    echo(a, n);
    cout<<echo(a,n);
    system("pause");
    return 0;
}

float
echo(float a[], int k) {
    for (int i = 0; i < k; ++i)
        cout << i << ":\t" << a[i] << endl;;
return(a[k]);
}


But you would still find on execution that there is still the presence of that unknown number.Could you tell me why?

I am using a Dev compiler on a Windows XP platform.
  #7  
Old 13-Sep-2008, 01:13
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: How to retrieve arrays from functions?


Quote:
Originally Posted by zalezog
But in my original program,I want the same function to return the whole array to my
CPP / C++ / C Code:
main()
.Then i want my program to again display the contents of the array.
This description does not match the modifications made. The return value from your function does not return the array, the return value from your function is a single float.

You also mention that you get some funky value. Look at what you are actually returning -- a[k] is the first element past the end of the array. If the number of array elements is 4, the range of valid subscripts is from 0 - 3. a[4] is invalid in that it has not legally been allocated nor has a value been assigned to this location. Errors made/assumed with 0-based subscripting is a common mistake made by newcomers to C and/or C++ alike.

It appears that you have made a number of erroneous assumptions about how C++ treats arrays. Other languages deal with them differently by usually ascribing much more functionality. Given that C & C++ are both languages which intentionally abstract the underlying assembly language (& little more...), arrays are merely blocks of memory which are indexed from the array's beginning address. This is why 0-based indexing is used. All elements are described relative to the beginning address of the array.
Last edited by ocicat : 13-Sep-2008 at 02:16.
  #8  
Old 13-Sep-2008, 02:15
zalezog zalezog is offline
Junior Member
 
Join Date: Oct 2007
Posts: 33
zalezog will become famous soon enough

Re: How to retrieve arrays from functions?


Returning
CPP / C++ / C Code:
return(a[k-1]);
does not help as the last number repeats itself.and changing
CPP / C++ / C Code:
cout<<echo(a,n-1)
in main() truncates the last element ?How do you modify it?
  #9  
Old 13-Sep-2008, 02:36
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: How to retrieve arrays from functions?


Quote:
Originally Posted by zalezog
Returning
CPP / C++ / C Code:
return(a[k-1]);
does not help as the last number repeats itself.and changing
CPP / C++ / C Code:
cout<<echo(a,n-1)
in main() truncates the last element ?
Correct. You are now describing the exact behaviour of the code presented.
Quote:
How do you modify it?
What is your intention?

The last statement in the function:
CPP / C++ / C Code:
return a[k - 1];
...returns the value of the k - 1th element of the array. Nothing more.

The statement::
CPP / C++ / C Code:
cout << echo(a, n - 1);
...will print the value of each array element excluding the last (accomplished by executing the function itself...), followed by printing the next to last element again.

It appears that you are making the assumption that the following line of code:
CPP / C++ / C Code:
cout << a;
...will again print out each element within the array. It doesn't. To print each array element, you will again need to iteratively step through the array just like what was done within the function & print each element individually. As stated before, C++ merely treats an array as a collection of contiguous elements. The cout object does not understand arrays; it only understands what to do with the fundamental element type.

I can only guess that what you are wanting to do is something similar to the following:
CPP / C++ / C Code:
#include <iostream>

using namespace std;

float* echo(float[], int);

int
main() {
    const int size = 4;
    float a[size];
    int n;

    do {
        cout << "enter size:" << endl;
        cin >> n;
    } while (n <= 0 || n > size);

    for (int i = 0; i < n; ++i) {
        cout << i << ":" << endl;
        cin >> a[i];
    }

    float *b = echo(a, n);
    for (int i = 0; i < n; ++i)
        cout << i << ":\t" << b[i] << endl;

    return 0;
}

float*
echo(float a[], int k) {
    for (int i = 0; i < k; ++i)
        cout << i << ":\t" << a[i] << endl;;

    return a;
}
  #10  
Old 13-Sep-2008, 02:54
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: How to retrieve arrays from functions?


Quote:
Originally Posted by zalezog
Can you suggest an alternative of doing the same thing?
Two comments:
  • See the example appended to my last response.
  • Describe exactly what it is that you intend to accomplish.
There is little difference between my previous example & the following:
CPP / C++ / C Code:
#include <iostream>

using namespace std;

void echo(float[], int);

int
main() {
    const int size = 4;
    float a[size];
    int n;

    do {
        cout << "enter size:" << endl;
        cin >> n;
    } while (n <= 0 || n > size);

    for (int i = 0; i < n; ++i) {
        cout << i << ":" << endl;
        cin >> a[i];
    }

    echo(a, n);
    for (int i = 0; i < n; ++i)
        cout << i << ":\t" << a[i] << endl;

    return 0;
}

void
echo(float a[], int k) {
    for (int i = 0; i < k; ++i)
        cout << i << ":\t" << a[i] << endl;;
}
I am not against returning the address of the array as the return value of the function, however, it is the same array defined earlier in main().

It is not clear whether you understand that passing the array to the function is accomplished by merely passing its beginning address. This is why I question the value of returning the array from the function.
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

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

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Arrays as function arguments - return arrays from functions pisuke C Programming Language 2 25-Jul-2007 12:03
Pointers, Functions, arrays allican57@yahoo C++ Forum 12 10-Nov-2006 15:17
Shapes Functions Version 2 - Arrays! Cecil C Programming Language 1 09-Jul-2006 21:39
structure arrays... how to pass to functions? tones1986 C++ Forum 2 08-May-2006 02:50
Noob question on c arrays and functions brett C Programming Language 1 20-Apr-2005 04:59

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 08:25.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.