Passing of value between Function (QUESTION)

I get this code over my pass year question
therefore there is a question that i do not understand
why the output is 3??For "numbers[0]"
there is no "&" in the void function, so under my thought, the value of y[0] should not be sent over back to the main function

Thanks in advance




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<cmath>
#include<iomanip>
#include<string>
#include <fstream>
using namespace std;



void m(int x,int y[]);


int main()
{
	int number=0;
	int numbers[1];
	
	m(number,numbers);
	cout<<"number is"<<number<<endl
		<<"and number[0]; is"<<numbers[0]<<endl;
	



system("pause");
return 0;
}
void m(int x,int y[])
{
	x=3;
	y[0]=3;
}
Arrays are a bit special. When you pass an array like this you will actually be passing a pointer to the first element in the array. line 28 could have been written void m(int x,int* y) to better show what's going on.
Thanks for the reply Peter!
so I can deduce that, the elements in the array y is equal to the element in the array numbers ??

Erm...
for the pointer that part ,
do array y point to array numbers ??
so as we change the value in array y, it will eventually change the value in array numbers?
y is not an array. It's a pointer that points to the elements in the numbers array.
Ohh!
Thanks for lightening the path
now i get it

so it is a pointer that automatically generated whenever you passing by a array over a function...
Last edited on
Yeah. Let me clarify things:

Think of this code here:
1
2
int Array[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int * ArrayPointer = Array;


Now let's take a deep look at ArrayPointer:
Array = (Address of Memory where Data is stored at, let's say 0x01010101)
ArrayPointer = Array = 0x01010101
ArrayPointer[0] = (First element found at 0x01010101 in memory)
ArrayPointer[0] = Array[0] = *ArrayPointer = *Array = 1 (See over why 1)
ArrayPointer[1] = Array[1] = *(ArrayPointer+1) = *(Array+1) = 2
etc etc...
Last edited on
But...
Does this actually same as if we use the "&" reference sign for normal variable ??
To returning the value back to the function ?
If you mean...
1
2
int Variable = 0;
int * Pointer = &Variable;

*Pointer = Pointer[0] = Variable = 0

But if you use Pointer[1] or Pointer[2] you will go out of bounds, as you don't "own" that part of the memory.

So, you can still use it with '*' operator but cannot use the [] operator to go out of bounds.
Last edited on
Topic archived. No new replies allowed.