天天看点

结构体数组与指针习题

《程序设计基础-c语言》杨莉 刘鸿翔  
ISBN-978-7-03-032903-5  
p165
习题6
           

1.写出下述程序的运行结果

#include<stdio.h>
struct s
{
	int x,*y;
}*p;
int data[]={10,20,30};
struct s array[]={ 100,&data[0],200,&data[1],300,&data[2]
};
void main()
{
	p=array;
	printf("%d\n",++p->x);
	printf("%d\n",++*p->y);
	printf("%d\n",*++p->y);
}
           

编译后结果如下:

结构体数组与指针习题

思路:

第一个输出语句

printf("%d\n",++p->x);

根据c语言运算符的优先级与结合性,

->

优先级最高,结合方向

从左到右

++

优先级第二,结合方向

从右到左

  1. 指针p指向结构体

    struct s array[]

    数组第一个元素100
  2. 指针p指向结构体

    struct s array[]

    数组第一个元素100

第二个输出语句

printf("%d\n",++*p->y);

++

*

优先级相同
  1. 指针p先指向y,即结构体

    struct s array[]

    第二个元素

    &data[0]

    (代表数组

    data[0]

    的地址)
  2. 指针p先指向y,即结构体

    struct s array[]

    第二个元素

    &data[0]

    (代表数组

    data[0]

    的地址)
  3. 在与

    *

    结合,即取内容,即

    data[0]

    的值10,

    ++

    ,即内容+1,结果为11

第三个输出语句

printf("%d\n",*++p->y);

  1. 指针p指向y,即指向结构体

    struct s array[]

    数组

    &data[0]

    的地址
  2. 然后与

    ++

    结合,指针移动一个结构体,指向

    &data[1]

    的地址
  3. 在与

    *

    结合取地址,结果为20

继续阅读