I'm asking this question to relieve myself of the confusion I've been having about the following program. I know using an array in certain contexts will make the array to decay to a single pointer to its first element. I have a function that returns this array by pointer (this function is created using new[]
). Will the array decay, causing the pointer to point only to the first element? Here is an example:
int *foo() {
int *t = new int[10];
return t;
}
int main() {
int *p = foo();
}
This is where the confusion follows. I don't know if p
points to the first element or to the entire array. So I have the following questions:
- Does returning the array by pointer cause the decay of it (and consequentially cause a memory leak)?
- Does
p
point to the array's first element? - Does using
delete[]
onp
cause undefined behavior if the above two are true?
I'm hoping these questions can be answered so I can fully understand this program. Thank you.