Consider the following code :
void populate(int *arr)
{
for(int j=0;j<4;++j)
arr[j]=0;
}
int main()
{
int array[2][2];
populate(&array[0][0]);
}
There was a discussion regarding this on a local community whether the code is valid or not(Am I supposed to mention its name?). One guy was saying that it invokes UB because it violates
C++ Standard ($5.7/5 [expr.add])
"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined."
But I don't see anything wrong with the code,the code is perfectly OK for me.
So, I just want to know is this code valid or not? Am I missing something?
What Is a Validation Code? A validation code—also known as a CVV, CV2, or CVV2 code—is a series of three or four numbers located on the front or back of a credit card. It is intended to provide an additional layer of security for credit card transactions that take place online or over the phone.
To ensure you have valid code, simply run your code through a code validator, like the W3C Code Validator. There are many other tools available that incorporate the same test suite as the W3C Validator. Note: ARIA attributes will be marked as errors in some Web pages like pre-HTML5 pages.
Your array
is two arrays of int[2]
, while your function populate()
treats it as a single array of int[4]
. Depending on exactly how the compiler decides to align the elements of array
, this may not be a valid assumption.
Specifically, when j
is 2 and you try to access arr[2]
, this is outside the bounds of main
's array[0]
and is therefore invalid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With