Essentially my question is that, in C and C , if I update a variable that I have previously placed in an array, why does it not update the array?
Ex:
int var = 0;
int list[1];
list[0] = var;
var = 1;
printf("%i", list[0]);
I don't understand why it is printing 0
instead of 1
.
CodePudding user response:
list[0] = var;
copies the value in var
into list[0]
- var
and list[0]
are two separate int
s.
If you want changes to one variable to be seen through another varible, you need to use pointers or references. Example:
int main() {
int var = 0;
int* list[1]; // an array of pointers to `int`
list[0] = &var; // list[0] now points at `var`
var = 1;
printf("%i\n", *list[0]); // dereferencing list[0] to get the value in `var`
}
Output:
1
CodePudding user response:
The variable var
is a separate object relative to the array list
int var = 0;
int list[1];
They occupy different extents of memory.
In this assignment
list[0] = var;
the copy of the value of the variable var
is assigned to another object list[0]
. var
and list[0]
have no any relation between each other.
You could declare an array of pointers like for example
#include <stdio.h>
int main( void )
{
int var = 0;
int * list[1];
list[0] = &var;
var = 1;
printf( "*list[0] = %d\n", *list[0] );
}
The program output is
*list[0] = 1
In this case the pointer list[0]
points to the variable var
. So using the pointer you can output the current value of the variable var
.
Pay attention to that even in C you may not declare an array of references. Similarly to the shown above approach with pointers you could declare an array of objects pf the type std::reference_wrapper
as for example
#include <iostream>
#include <functional>
int main()
{
int var = 0;
std::reference_wrapper<int> list[1] = { var };
var = 1;
std::cout << "list[0] = " << list[0].get() << '\n';
}
The program output is
list[0] = 1