简体   繁体   English

数组输入中的括号是什么意思

[英]What brackets in array input mean

为什么在某些动态数组声明中,我们需要将数组名称放在方括号中:

(*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) ? x = a + b*cx = (a + b)*cx = 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: 或像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. 答案是它像B一样执行,因此,如果您真的想要A,则需要显式添加括号。

An example where you would want A is when allocMat is a pointer to an array. allocMat是指向数组的指针时,您需要A的示例。

An example where you would want B is when allocMat is an array of pointers. allocMat是一个指针数组时,您想要B的示例。

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. 在上面的代码片段中, allocMat是指向数组的指针。 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. Allocmat大概是指向数组的指针。

The parentheses are needed to get the indirection correctly. 需要括号才能正确获取间接地址。 So (*allocMat)[count++] is the same as allocMat[0][count++] . 因此(*allocMat)[count++]allocMat[0][count++] Would you omit the parentheses, *allocMat[count++] would be equal to allocMat[count++][0] which is completely different. 如果您省略括号, *allocMat[count++]将等于allocMat[count++][0] ,这是完全不同的。 This is because operator precedence - [] binds slightly tighter than * . 这是因为运算符优先级- []绑定比*绑定更紧密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM