so I'm going to have to ask a very basic question which I am kind of shy to ask since I have been learning c++ for 2 years on and off
anyway my question is as follows,here I get some errors
how come this isn't allowed we are returning a pointer to an array and I know this is allowed because arrays decay down to pointers to their first element
but how come this is giving me an error?
also when I return the pointer from the array function isn't this pointer pointing to memory that has gone out of scope?
so number[5] = out of scope memory?
thanks
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int* array(){
int numbers[] = {1,23,4,45,6};
return numbers;
}
int main() {
int number[5] = array();
}
#include <iostream>
usingnamespace std;
int* array(){
int numbers[] = {1,23,4,45,6};
return numbers;
}
int main() {
constint* arr = array();
for(int i = 0; i < 5; i++){
cout << arr[i];
}
}
I'm not surprised this code compiles but I am quite surprised the code above crashes,I thought by making the int pointer const I am keeping the array which was returned in scope?
Yes. You allocated 5 elements [0]-[4]. So [5] is not a valid reference.
also when I return the pointer from the array function isn't this pointer pointing to memory that has gone out of scope?
Yes, numbers goes out of scope when array() exits.
I am quite surprised the code above crashes,I thought by making the int pointer const I am keeping the array which was returned in scope?
In the second snippet, numbers goes out of scope at line 8. The fact that you declared arr as const only means that you have told the compiler you're not going to modify arr within main(). The const declaration has nothing to do with whether the pointer returned by array() is in scope or not. It's not.
No. As I explained before, you're returning a pointer to something that has gone out of scope. Therefore it no longer exists.
also making a variable static how will this prolong the life of a variable?
Making a variable static will make the variable exist for the life of the program. Thereby making it legal to return a pointer to it since it will not go out of scope.
I thought static just means the variable belongs to the class instead of instances of it
Using static on a class member variable makes the member variable exist for the life of the program. Since the member variable is scoped within the class name, you can think of it as belonging to the class, but the lifetime of a static member variable is still for the lifetime of the program.