一元 '*' 的类型参数无效(有“int”)
我正在解决科学家和工程师的 C 的以下作业问题:
Given the following declarations and assignments, what do these expressions evaluate to?
int a1[10] = {9,8,7,6,5,4,3,2,1}
int *p1, *p2;
p1 = a1+3;
Line 14: p2 = *a1[2];
我正在尝试使用 gcc 编译此代码,但是当我这样做时,它会给出以下错误:
w03_3_prob15.c: In function 'main':
w03_3_prob15.c:14:7: error: invalid type argument of unary '*' (have 'int')
我正在使用以下命令进行编译:
gcc -o w03_3_prob15 w03_3_prob15.c -std=c99
我真的不知道该怎么做。您对如何修复此错误有任何想法吗?
I'm working on the following homework problem from C for Scientists and Engineers:
Given the following declarations and assignments, what do these expressions evaluate to?
int a1[10] = {9,8,7,6,5,4,3,2,1}
int *p1, *p2;
p1 = a1+3;
Line 14: p2 = *a1[2];
I'm trying to compile this code with gcc, but when I do so, it gives me the following error:
w03_3_prob15.c: In function 'main':
w03_3_prob15.c:14:7: error: invalid type argument of unary '*' (have 'int')
I'm using the following command to compile:
gcc -o w03_3_prob15 w03_3_prob15.c -std=c99
I'm really not sure what to do. Do you have any ideas on how to fix this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该行无法编译,因为它在书中是不正确的。来自作者的勘误页面:
The line doesn't compile because it's incorrect in the book. From the author's Errata page:
在 C 中,一元
*
仅为指针定义。p2
是一个int*
。a1
是一个int[]
。a1[2]
是一个int
。[]
的优先级高于一元*
,因此您有*(a1[2])
,它不是合法的表达式。这就是编译器停止的原因。我可以想到两种可能的解决方案。您想要哪一个,取决于您想要做什么。
In C, unary
*
is only defined for pointers.p2
is anint*
.a1
is anint[]
.a1[2]
is anint
.[]
has higher precedence than unary*
, so you have*(a1[2])
, which is not a legal expression. This is why the compiler is halting.I can think of two possible solutions for this. Which one you want, depends on what you are trying to do.
p2
的类型为int*
。a1[2]
的类型是int
,因此*a1[2]
没有意义。您确定您准确地复制了作业问题吗? (如果是这样,那就是家庭作业问题。它们就会发生。)The type of
p2
isint*
. The type ofa1[2]
isint
, so*a1[2]
is meaningless. Are you sure you copied the homework problem exactly? (If so, bad homework problem. They happen.)