I have a program here:
#include<iostream>
using namespace std;
void f1(int* x){
for (int i = 0; i < sizeof(x); i++) {
cout<<x[i]<<endl;
}
}
void f2(int* x) {
cout<<x<<endl;
}
int main() {
int a=3;
int a1[3]={2,3,1};
f1(a1);
f2(a);
}
The function f1 allows me to pass an array as the argument to function but does not allow an integer variable to be passed as an argument.
How is this justified? Does this have anything with the fact that the pointer takes 8 bytes of memory while integer takes only 4?
I get the following error when I run the code:
invalid conversion from 'int' to 'int*'
argument of type 'int' is incompatible with parameter of type 'int'
what does this mean?
I'm fairly new to programming so m sorry if the question seems stupid.
sizeof(x)issizeof(int*), not the size of the array.intis not the same as anint. A pointer represents an address in memory of the computer; you can get an address of anintusing the&operator (it's name is address-of-operator):f2(&a);. By the way, be aware thati < sizeof(x)ain't does what you think it should.void f1(int* begin, int* end)and call it withf1(a1, a1+3);andf1(&a, &a + 1);