What's the difference between the below 2 codes in main() function? Both are filled with 0s. I expect array q to be filled with 0s since it's value-init. However array p is also filled with 0s.
int main() {
int *p = new int[3];
int *q = new int[3]();
}
Thanks for help
CodePudding user response:
q
is guaranteed to be filled with 0s.
p
will be pointing to uninitialized memory and therefore will filled with whatever data happened to be left in that memory location from previous usage... it might be zeroes, but it might be anything else; you can't rely on it being set to any particular value, so you have to write to that memory before you read from it or you'll invoke Undefined Behavior.
CodePudding user response:
()
is the initializer. This particular initializer sets every element of the array to zero. If you don't provide an initializer, default initialization takes place, which, in case of int *p = new int[3];
, results in an array filled with indeterminate values ("garbage") which may or may not be 0
;