为什么在某些动态数组声明中,我们需要将数组名称放在方括号中:
(*allocMat)[count++] = row;
It's about operator precedence, ie which part of the statement is executed first.
Like in simple math. Is x = a + b*c
executed like x = (a + b)*c
or like x = a + (b*c)
?
So for your code the question is: Is *
"stronger" than []
or is it the opposite?
Consider just doing:
*allocMat[count++] = row;
How would you expect that to be executed?
Like A:
(*allocMat)[count++] = row;
or like B:
*(allocMat[count++]) = row;
The answer is that it's executed like B so if you really want A then you need to explicit add the parenthesis.
An example where you would want A is when allocMat
is a pointer to an array.
An example where you would want B is when allocMat
is an array of pointers.
This is because of operator precedence . The array subscript operator []
has higher priority than the unary dereference operator *
. So, unless the parenthesis is used, a statement like
*allocMat[count++] = row;
will be parsed as
* (allocMat[count++]) = row;
which is not desired.
To properly evaluate the statement, we need to first dereference the pointer, and then, index onto it, like
(*allocMat)[count++] = row;
In the above snippet, allocMat
is a pointer to an array. So, unless, the dereference is forced on higher priority, the subscripting operator []
, which has higher priority, will be taken into account first and will result in incorrect evaluation.
Allocmat is presumably a pointer to an array.
The parentheses are needed to get the indirection correctly. So (*allocMat)[count++]
is the same as allocMat[0][count++]
. Would you omit the parentheses, *allocMat[count++]
would be equal to allocMat[count++][0]
which is completely different. This is because operator precedence - []
binds slightly tighter than *
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.