2011-10-18 105 views
1

我正在下面作业的问题从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]; 

我试图编译这段代码用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 

我真的 不知道该怎么办。你有什么想法如何解决这个错误?

+1

你不是要编译它做家庭作业。你应该能够看到它并知道答案。但是您发布的代码已损坏。回到这本书并检查你输入的是否正确。 –

+0

我刚刚检查了我是从书中准确地输入了代码,而且我做到了。请注意,添加了“第14行:”以显示错误的位置。 –

回答

7

该行不能编译,因为它在本书中不正确。从author's Errata page

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

修好了!感谢您将这一页面指向我。这将在未来派上用场。 –

1

p2的类型是int*a1[2]的类型是int,所以*a1[2]是没有意义的。你确定你完全抄袭了作业问题吗? (如果是这样,坏的功课问题,他们发生。)

2
p2 = *a1[2]; 

在C,一元*只为指针定义。 p2int*a1int[]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. 
相关问题