If I have a function as an array NumArray and it is not modified by the function, how will it appear in the parameter list? Will it be just as it is entered? Not sure I understand this totally.
Thanks!!
If I have a function as an array NumArray and it is not modified by the function, how will it appear in the parameter list? Will it be just as it is entered? Not sure I understand this totally.
Thanks!!
To pass an array to a function you could do this:
In that example you could not modify the contents of the array and n would be the size of the array. Does that help?Code:#include<iostream> using namespace std; void someFunc(const int* array, int n) { for (int i=0;i<n;i++) cout<<array[i]<<endl; } int main() { int array[10]; for (int i=0;i<10;i++) array[i]=i; someFunc(array,10); }
"Think not but that I know these things; or think
I know them not: not therefore am I short
Of knowing what I ought."
-John Milton, Paradise Regained (1671)
"Work hard and it might happen."
-XSquared
Yes it helps some. Can we substitue NumArray in there somewhere? Also, can you make comments so I know what things are doing? That is what helps me learn the most!
Thanks!!!
Whenever you pass an array, you pass a pointer. Regarding functionality, the function declarations below are the same:
Both function have a second parameter, as you should also provide the array's size, in order to prevent step-by errors - meaning you try to read or write data pass the end of the array. Passing the array's size allows necessary safety checks which are recommended when working with arrays.Code:void f( int* array_in, int size_in ); // pass a pointer - actually it should point to the first element of the array void g( int array[], int size_in ); // pass an array
When calling the function, you can do following:
Using the second, simplified form is shorter and safer, as you surely pass the starting address of the given array (the compiler ensures that).Code:int anArray[5] = {0, 1, 2, 3, 4}; // declaration and initilization f( &anArray[0], 5 ); // passing the address of the first element f( anArray, 5 ); // simplified syntax
As arrays are passed by pointers, not by value, their contents can be changed in the called function. In order to disallow this, you should pass a pointer to constant, as specified by JaWib.
Speaking of classical arrays, their size does not change at runtime. Of course, you can write your own Array class, which does change dinamically, but you should also check STL vector class for example. However, this is a little bit advanced issue.
Last edited by Carlos; 06-04-2004 at 01:21 AM.
[R]evolution!
Programming related articles, downloads, demos
Since the array is not to be changed, would it be possible just to so something like :
Code:int myFunc(const int array[], int size);
maybe i should have just read the post above beforeOriginally Posted by ryan_germain