一元 '*' 的类型参数无效(有“int”)

发布于 2024-12-10 09:08:30 字数 636 浏览 1 评论 0原文

我正在解决科学家和工程师的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

给我一枪 2024-12-17 09:08:30

该行无法编译,因为它在书中是不正确的。来自作者的勘误页面

Page 438, line 17 from the bottom.
p2 = *a1[2]; 
should be  p2 = &a1[2];

The line doesn't compile because it's incorrect in the book. From the author's Errata page:

Page 438, line 17 from the bottom.
p2 = *a1[2]; 
should be  p2 = &a1[2];
或十年 2024-12-17 09:08:30
p2 = *a1[2];

在 C 中,一元 * 仅为指针定义。 p2 是一个int*a1 是一个int[]a1[2] 是一个int[] 的优先级高于一元 *,因此您有 *(a1[2]),它不是合法的表达式。这就是编译器停止的原因。

我可以想到两种可能的解决方案。您想要哪一个,取决于您想要做什么。

*p2 = a1[2]; // Assigns the value of the second int in the array to the location
             // pointed to by p2.
p2 = &a1[2]; // Assigns the location of the second int in the array to p2.
p2 = *a1[2];

In C, unary * is only defined for pointers. p2 is an int*. a1 is an int[]. a1[2] is an int. [] 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 = a1[2]; // Assigns the value of the second int in the array to the location
             // pointed to by p2.
p2 = &a1[2]; // Assigns the location of the second int in the array to p2.
自由如风 2024-12-17 09:08:30

p2 的类型为 int*a1[2] 的类型是 int,因此 *a1[2] 没有意义。您确定您准确地复制了作业问题吗? (如果是这样,那就是家庭作业问题。它们就会发生。)

The type of p2 is int*. The type of a1[2] is int, so *a1[2] is meaningless. Are you sure you copied the homework problem exactly? (If so, bad homework problem. They happen.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文