宏数组访问的语法错误
我试图从二维数组中读取值并将它们相乘以创建一个新的数组。这并不完全重要。
我创建了一个宏来读取值,而不是一个函数,理论上更有效,但我遇到了一个我无法弄清楚的语法错误。问题出
// compute and write the value for the result array
writearr( result, n, r, c, ( READ(r, c, A*) * READ(c, r, A*) ) );
在函数头
void newarr(int n, int* A, int* result)
宏
#define READ(a, b, arr) (arr[a][b])
宏上,当我尝试编译这个
gcc -Wall -O2 -c -o placeholder.o placeholder.c
placeholder.c: In function âwritearrâ:
placeholder.c:26: error: expected expression before â[â token
make: *** [placeholder.o] Error 1
时,我得到了答案,但我不太明白问题是什么。
I'm attempting to read values from a 2-dimensional array and multiply them to make a new array array. This isn't entirely important.
I have created a macro to read the values instead of a function to theoretically be more efficient, but I'm having a syntax error that I can't figure out. The line of issue is
// compute and write the value for the result array
writearr( result, n, r, c, ( READ(r, c, A*) * READ(c, r, A*) ) );
with function header
void newarr(int n, int* A, int* result)
The macro is
#define READ(a, b, arr) (arr[a][b])
and when I try to compile this I get
gcc -Wall -O2 -c -o placeholder.o placeholder.c
placeholder.c: In function âwritearrâ:
placeholder.c:26: error: expected expression before â[â token
make: *** [placeholder.o] Error 1
but I can't quite figure out what the issue is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您需要将宏参数括在括号中。
其次,您应该使用
A
而不是A*
来取消引用。A*
根本无效,但您可能想要&A
(这实际上也是不正确的)?第三,在这种情况下,宏实际上并没有比仅访问数组带来任何优势。
第四,您将 A 声明为一维数组,不能将其用作多维数组。获取一维数组的地址不允许自动切换到“下一个”行,因为 C++ 不知道该行有多大。
First of all, you need to enclose your macro arguments in parentheses.
Second, you should use
A
instead ofA*
for dereferencing.A*
is not valid at all, but you wanted perhaps&A
(which as actually incorrect as well)?Third, in this case the macro doesn't actually bring any advantage against just accessing the array.
Fourth, you declared A as a one-dimentional array, you cannot use it as a multidimentional one. Taking an address of a single-dimensional array doesn't allow you to switch to the "next" row automatically, as C++ doesn't know how large the row is going to be.
我不明白这里使用 READ 宏有什么意义。如果您必须使用此语义,您需要执行以下操作:
I don't see the point of using READ macro here. If you have to user this semantics, you need to do: