C++ program for address and variables - c++

The output for this code is:
9
And I'm not sure what it changes in the function add1. And also what does this &n mean and what does it do when we assign the i to &n?
#include <iostream>
using namespace std;
int add1(int &n){
n++;
return n;
}
int main(){
int m = 0;
for (int i = 0; i < 5; i++){
m += add1(i);
}
cout << m ;
cout << "\n\n";
return 0;
}

When & is used in a parameter list, it will cause that parameter to be passed as a reference to the function.
What this means is that n in your function add1, will point to the same space in memory as i in your main function. Changes to n will also be reflected in i, as they will simply act as different names for the same thing.

Variable i is passed into add1 as a reference parameter, so every round i is increased by two:
1st round: i = 0, m = 1
2nd round: i = 2, m = 4
3rd round: i = 4, m = 9

If you have a function like this
int add1( int n )
^^^^^
{
n++;
return n;
}
and call it like
m += add1(i);
Then the function deals with a copy of the value of vatiable i.
You can imagine it the following way if to build it in the body of the loop
for ( int i = 0; i < 5; i++ )
{
// m += add1(i);
// function add1
int n = i;
n++;
m += n;
}
When a function is declared like this
int add1( int &n )
^^^^^
{
n++;
return n;
}
Then it means that the parameter is a reference to the corresponding original argument. You can consider it just as an alias for the argument.
In this case you can imagine it the following way if to build it in in the body of the loop
for ( int i = 0; i < 5; i++ )
{
// m += add1(i);
// function add1
i++;
m += i;
}
So the variable i is changed twice in the function add1 because it is directly used in the function by means of the reference n and in the control statement of the loop.

Here we are passing a parameter to the add1() function by using pass by reference. To pass a variable by reference, we simply declare the function parameters as references rather than as normal variables.
In above code,
int add1(int &n){ // n is a reference variable
n++;
return n;
}
When the function is called, n will become a reference to the argument. Since a reference to a variable is treated exactly the same as the variable itself, any changes made to the reference are passed through to the argument!

Related

function with 2 parameters without value

Is this function have any sense? if I didn't define the value of p_var1[] and p_size?
Just to know if it make sense, I have bigger code, but as a beginner, for me, if there is no values for these variables, that is weird.
First function:
int max1(int p_values[15][15])
{
int max_value;
for(int i=0; i < 15; i++)
{
int max_v = fnc(p_values[i], 15);
if( max_value < max_v)
{
max_value = max_v;
}
}
return max_value;
}
and second
//p_var1[] - is an array of values
//p_size - is the size of array
int fnc(int p_var1[], int p_size)
{
int max_value;
for (int i = 0; i < p_size; i++)
{
if (max_value > p_var1[i])
{
max_value = p_var[i];
}
}
return max_value;
}
This code isn't a full program, it's just a function definition. Here, a function called fnc is declared that can be called with parameters. Here's an example of a full program using it:
//p_var1[] - is an array of values
//p_size - is the size of array
int fnc(int p_var1[], int p_size)
{
int max_value;
for (int i = 0; i < p_size; i++)
{
if (max_value > p_var1[i])
{
max_value = p_var[i];
}
}
return max_value;
}
int main() {
int lst[5] = {10, 2, 6, 4, 8};
int max = fnc(lst, 5); // max = 10
return 0;
}
I guess you wrote fnc(p_values[i], 15) without knowing what it means? Not the best approach, but asking about it shows promise. When this expression is reached, the fnc identifier says that we're going to pause the execution of the current function (max1) and jump to execute the function fnc. Once that function finishes, the returned value will be the value of the expression and execution of max1 can resume. The stuff in the parentheses says that as we jump to fnc, assign p_var1 = p_values[i] and p_size = 15 (the first parameter is assigned the first argument, and the second parameter is assigned the second argument). If you're confused by the terms "parameter" and "argument", see What's the difference between an argument and a parameter?
So when you call fnc you do define the value of p_var1 and p_size (for that function call). (Wikipedia has an article with an example that covers this also, and you might find some useful information in the rest of that article.)

Pointer of Two dimensional array to function c++

Im kind of begginer in C++, just to programming in PHP and JAVA, I have problem to make a pointer to 2d array, then use this pointer in different function and cout values of [0] and [1].
There is part of my script.
int size_dd = 5;
int dd[size_dd][2];
for (int i = 0; i < size_dd; i ++)
{
dd[i][0] = 2 * i + 10;
dd[i][1] = 4 * i + 20;
}
I can read the dd[i][0] in main function but I cannot call them in function read(int* twodarray), as it returns int[int] and the 2nd parameter from array is lost.
Thing is that I need to make pointer to this array and call it in other function.
But the problem is when I handle *dd in to the function, it return that dd is int[int] value instead of int[int][int], how can I resolve it?
Your function should have following signature:
void fooByPtr(int(*arr)[5][6]) {
(*arr)[4][4] = 156;
}
// Call ex:
int dd[5][6];
fooByPtr(&dd);
You can also do it with reference and template:
void fooByRef(int (&arr)[5][6]) {
arr[4][4] = 156;
}
template<int N, int M>
void fooByRefTempl(int(&arr)[N][M]) {
arr[4][4] = 156;
}
Some other comments to your code (also the one from comment):
You can create arrays using constant values as sizes, so this is wrong:
int size_dd = 5;
and should be:
const int size_dd = 5;
in your fun_call you should dereference your array: (*dwu_wymiar) before indexing it.
finally, change funCall(int(*dwu_wymiar)[][2], to int(*dwu_wymiar)[5][2], as in my example above.

Simple C++ swap function

Why is it that if I have a function like this, to swap two numbers, it doesn't work[swap], (I know I can do this by declaring pointers in the prototype, and then pass the address of the respective variables in main()), but works for array, without having to pass pointers and addresses.
Doesn't work
void num_exchange(int m, int n);
int main(){
int num1 = 5;
int num2 = 6;
num_exchange(num1 , num2 );
cout << "num1 =" << num1 << endl;
cout << "num2 =" << num2 << endl;
return 0;
}
void num_exchange(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}
Works
void arr_exchange(int [], int);
int main(){
int n[7] = { 0, 0, 0, 0, 0, 0, 0 };
arr_exchange(n, 7);
for (int i = 0; i < 7; i++)
cout << n[i] << " ";
return 0;
}
void arr_exchange(int x[], int){
for (int i = 0; i < 7; i++)
x[i] = 1;
}
void num_exchange(int m, int n){
int temp;
temp = m;
m = n;
n = temp;
}
modifies copies of the input integers. To make your code work use
void num_exchange(int& m, int& n){
int temp;
temp = m;
m = n;
n = temp;
}
instead (note the & in the first line). This is called passing by reference. In general, use std::swap to swap things.
void arr_exchange(int x[], int){
for (int i = 0; i < 7; i++)
x[i] = 1;
}
works because in C++
void arr_exchange(int x[], int){
is equivalent to
void arr_exchange(int* x, int){
So here a pointer is passed and thus the original data is modified.
Your num_exchange() takes its arguments by value, i.e., it sees copies of the original value. When you swap them, the copies are swapped but the originals are not touched. When you swap arrays, instead a pointer to the array start is passed (built-in arrays are never copied directly in C++). Since the pointer references the original array rather than a local copy, swapping array elements results in a change visible even when the function is exited.
To pass the actual original objects to your num_exchange() function you'd either use pointers, too, or you'd use references, e.g.:
void num_exchange(int& m, int& n) {
// ...
}
Of course, the easiest approach to swapping elements is to use the standard or type provided swap() function although it is, admittedly, a bit awkward to use due to the extra using-directive:
using std::swap;
swap(num1, num2);
Functions are by default call by value.
what happens when a function call occurs???
When a function call occurs address of next instruction in program is pushed onto stack which tells the compiler where to return after function execution following that the function arguments(5 and 6) are pushed onto stack.
Inside function, these arguments are popped out of stack i.e. m=5,n=6 this means the actual arguments(num1,num2) are unaltered.
The function then executed with aliases of num1(i.e. m) and num2(i.e. n) after execution the address is popped out of stack to continue execution from where it is left.
In C, solution to this problem is to pass address of num1, num2 and use pointers to inside function to point them.
CPP added new concept called reference.A reference is another name given to the variable.
int & n1 = num1;
int & n2 = num2;
why it works with arrays??
Copying whole array is not feasible hence arrays are always pass by reference.The base address of array is passed to function hence whatever modifications done to the array in the function affects the real array.
the code you are loking for need two pointers because the function will copy the data you give them so:
void swap (int * a, int * b){
int temp = *a;
*a = *b;
*b = temp;
}

How can i return an array c++?

I am trying to generate some lotto numbers and return the array that contain these numbers but I cant go any further; Help please
void getLotto(int rad[7]) {
int numbers[7];
for (int i = 0; i < 7; i++) {
numbers[i] = rand() % 35 + 1;
}
for (int j = 0; j < 7; j++) {
int n = rand() % 35 + 1;
if (n == numbers[j]) {
numbers[j] = rand() % 35 + 1;
return;
}
}
}
Arrays can't be returned by functions. A common thing to do is to dynamically allocate the array and return a pointer to its first element. This will work in your case but will generate a requirement for the caller to manage the memory (delete[] the new[]'ed memory). That's why C++ provides us with standard array classes: Use and return a std::vector. If you have C++11 support, return std::array.
Following may help, using Fisher–Yates_shuffle:
// Fisher–Yates_shuffle
// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
std::vector<int> FisherYatesShuffle(std::size_t size, std::size_t max_size, std::mt19937& gen)
{
assert(size < max_size);
std::vector<int> res(size);
for(std::size_t i = 0; i != max_size; ++i) {
std::uniform_int_distribution<> dis(0, i);
std::size_t j = dis(gen);
if (j < res.size()) {
if (i != j) {
res[i] = res[j];
}
res[j] = 1 + i;
}
}
return res;
}
Live example
std::vector and std::array are better than regular arrays, but if you want to use regular arrays you can modify your function as follows:
// Arguments: renamed the array, added N (# of array elements)
void getLotto(int numbers[], size_t N) {
//int numbers[7]; // commented out local variable
for (int i = 0; i < N; i++) {
numbers[i] = rand() % 35 + 1;
}
for (int j = 0; j < N; j++) {
int n = rand() % 35 + 1;
if (n == numbers[j]) {
numbers[j] = rand() % 35 + 1;
return;
}
}
}
The brackets in int numbers[] indicates that the argument is an array, and what is actually passed is a pointer to the first element of the array. Modifying numbers in getLotto() modifies the array passed to the function.
The second argument is of type size_t because it is the platform-dependent alias for the unsigned integral type used by your system to represent the size of objects (like arrays).
This isn't as safe in that the function has to trust that numbers actually has N elements, but this is how you have a function modify a regular array instead of a container like std::vector.
You would call the function like this:
size_t N;
int numbers[N];
getLotto(numbers, N);
C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:
int * myFunction()
{
.
.
.
}
Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.
Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows:
#include <iostream>
#include <ctime>
using namespace std;
// function to generate and retrun random numbers.
int * getRandom( )
{
static int r[10];
// set the seed
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i)
{
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
// main function to call above defined function.
int main ()
{
// a pointer to an int.
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
When the above code is compiled together and executed, it produces result something as follows
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415
There are two main ways of accomplishing this.
note: I'm not sure what your second for loop is doing. I guess the intention was to ensure that the numbers are all unique? You might want to take a look at it as that is not what it is doing.
For the purposes of this question, I've cut it down to just generating the random numbers to populate the array.
The first is to take your code and fix it to put the generated numbers into the array that was passed in:
#include <iostream>
void getLotto(int numbers[7]) {
for (int i = 0; i < 7; i++)
{numbers[i] = rand() % 35 + 1;}
return;
}
int main()
{
srand(time(0));
int lotto_numbers[7];
getLotto(lotto_numbers);
for (int i = 0; i < 7; i++)
{std::cout<<lotto_numbers[i]<<std::endl;}
}
numbers isn't actually passed in as an int[] but instead as an int* pointing to the array. This means that any changes you make to it in the function are changed in the original data.
Bear in mind that you need to keep track of your array bounds though, as the array could be defined as
int lotto_numbers[6]
which means that
numbers[7]
would be out of bounds.
The second method is to create the array on the heap. This means that you don't need to pass in an array but you can instantiate it in the function
I'm not actually going to provide the code for this here. Mainly because for something simple like this, the memory management is more trouble than it is worth. (you need to remember to call delete[] for everything created on the heap etc).
Instead, lets use something with memory management built in:
#include <iostream>
#include <vector>
std::vector<int> getLotto() {
std::vector<int> numbers;
numbers.reserve(7);
for (int i = 0; i < 7; i++) {
//numbers[i] = rand() % 35 + 1;
//would work, but is unsafe as you could potentially reference somthing out of range
//this is safer:
numbers.push_back(rand() % 35 + 1);
}
return numbers;
}
int main()
{
srand(time(0));
std::vector<int> lotto_numbers = getLotto();
for (auto i = lotto_numbers.begin(); i != lotto_numbers.end(); i++)
{
std::cout<<*i<<std::endl;
}
}
The vector handles the memory management for you. The vector can be returned, and the returned vector will still point at the allocated memory on the heap we have just populated. We don't need to free it as this will be done automatically when the vector goes out of scope.

Why doesn't this array become zero?

I have written this piece of code:
#include <iostream>
using namespace std;
double function(int i)
{
static int Array[5] = {0};
for(int j = i ; j <= i ; j++)
{
Array[j+1] = Array[j]+1;
}
return Array[i+1];
}
int main()
{
for(int i = 0 ; i <= 4 ; i++)
{
cout << function(i) << endl;
}
return 0;
}
Which outputs 1,2,3,4,5
I am wondering why elements of Array at each call of function(i) doesn't become zero despite this piece of code :
static int Array[5] = {0};
The array is static, which means it gets initialized just once (the first time function is called). It keeps its existing items thereafter. If you remove the static keyword you will get 1, 1, 1, 1, 1 instead.
By the way, the for loop inside function is redundant (it's guaranteed to only execute exactly once).
When you use static keyword for declaring a variable inside a function. Then:
The variable is created when the function is called first time.
Thereafter the variable remains alive throughout the lifetime of the program &
The value of the variable persists between function calls.
What you observe is this property of the keyword static at work.
The Array is statics. static variables only initialize once. Therefor, Array becomes zero only on the first call.
if you remove the static keyword it will become zero on every call.
by the way the following code is very strange:
for(int j = i; j <=i ; j++)
because it only runs for j=i. So you can change the whole function by the following:
double function(int i)
{
static int Array[5] = {0};
Array[i+1] = Array[i]+1;
return Array[i+1];
}