Thank you kempofighter, this is a very interesting article. I intend to study it in greater detail.
I had tried something similar to your "method 1" for passing an array to a function before starting this topic. What I did was:
1 2 3 4 5 6 7
|
//functions.cpp
void testf(int n, int myArray[])
{
//function body
}
|
1 2 3 4
|
//functions.h
void testf(int n, int myArray[]);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
//main.cpp
int main()
{
int n;
printf("Input size of array:"); //prompt user for input
scanf("%d", &n);
myArray[n]; //declare the array
testf(n, myArray); //call the function
return 0;
}
|
Essentially, the difference with my initial post's version is that I removed the explicit array size in the function's declaration, passing it only indirectly as a second parameter. The result was that my code compiled fine, but the program crashes once the function is called.
I also tried the following variant after reading your article:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//main.cpp
int main()
{
int n2;
printf("Input size of array:"); //prompt user for input
scanf("%d", &n2);
const int n(n2);
myArray[n]; //declare the array
testf(n, myArray); //call the function
return 0;
}
|
So I get the input, then define a const int, and then I declare an array with that size. Again, the code compiles, but the program crashes upon the function call.
Have I misunderstood or misapplied "method 1" of your article? Any feedback is most appreciated.
As it is, my program uses several arrays and passes them into numerous functions for performing mathematical computations with them (it's an astronomy-related program), but the arrays themselves almost never have a size greater than 10, so I think that even your "method 1" might be applicable for the immediate requirements of this program. At the same time, I am looking forward to study your provided alternatives to C-Arrays in greater detail. I will probably redesign my whole program based on std::vector or std::deque in the immediate future.
Many thanks for any feedback. Regards,
Okaya