-
array as an argument
Say in main I have:
PHP Code:
int nums[5];
set_numbers(nums);
and I have a function called set_numbers() where I want to set the values for the numbers in the array:
PHP Code:
void set_numbers(int n[])
{
n[0] = 1;
n[1] = 2;
n[2] = 3;
n[3] = 4;
n[5] = 5;
}
that code works, but everywhere I read that you have to pass arrays by reference, and when I try to do that I get an error. Whats wrong with doing it how I'm doing it now, and how do I pass it by reference instead?
-
Nothing thats the perfect way to do it.
-
hmm.. ok well.. then can someone tell me how to make the iint nums[5] array in main the default array to use?
-
arrays are always passed by reference. What do u mean by default array?
-
like if i were passing an int i could do
PHP Code:
void set_numbers(int j = 1){}
i want to set the default value for int n[] to the array nums[] in the main function. can anyone tell me how to do that.
-
No way really to do that. A smart person always passes the size of the array as an parameter.
-
well then how would i get around that? I have a dll and I have an exe that tell the dll to create an instance of a class and i have to save that instance inside a vector. So don't I have to use a default vector?
-
Huh? If you are using a vector then use .size().
-
no. i'm not talking about the size. i'm talking about when i want to insert into a vector. the vector is outside of the function so how do i pass that vector to the function so i can insert the new instance in it?
-
judging from your original post maybe you mean something like this??
Code:
#include <iostream>
void set_numbers(int * ptr);
int main()
{
int * ptr = new int[5];
set_numbers(ptr);
std::cout << ptr[2];
delete ptr;
}
void set_numbers(int * ptr)
{
ptr[2] = 11;
}
-
Or if you want to pass the vector
Code:
void function(std::vector<type> &toPass);
-
hmm. i shouldn't have said anything about the main function because this question isn't literal. its in a dll and there is no main function. i have a vector that i create at the start and whenever the exe calls a function i want it to add an instance to that vector. prog-bman is that what you're suggestion will do?
-
Yes that will pass a vector from a function to another function and modify the contents within that vector.
-
i have a question though, what if i can't pass the vector from the exe that is calling the function?