1、将一个数(0x11FF)打印,再将它作为指针打印指向的内存单元中的值,再将所指向的内存单元的值再作为地址打印指向的内存单元的值,重复这个过程。
main()
{
int p = 0x11ff;
char ch = 0;
while (ch != 'q')
{
printf("p = %4x /t*p = %4x/n",p,(int)(*(int*)p));
p = (int *)(*(int*)p);
ch = getch();
}
}
2、编写一个结构体,打印结构体的首地址,再打印结构体中每个数的首地址,然后将结构体按照一个字节一个字节打印出来
main()
{
int i;
struct st
{
char c1;
char c2;
int i1;
int i2;
};
struct st st;
st.c1 = 'a';
st.c2 = 'b';
st.i1 = 1;
st.i2 = 2;
printf("&st = %x/n", &st);
printf("&c1 = %x/n", &st.c1);
printf("&c2 = %x/n", &st.c2);
printf("&i1 = %x/n", &st.i1);
printf("&i2 = %x/n/n", &st.i2);
for (i=0; i<sizeof(st); i++)
{
printf("%x ",(*(char *)(&st.c1+i)));
}
}
3、将偏移地址为0-3000的内存段看做375个具有以下结构的结构体
struct st { unsigned char int1; unsigned char int2; unsigned char int3; struct st far * pst; };
要求,将这段内存复制到一个结构体数组中,从数组中选出结构体的三个值的和在(200,400)范围内的变量,通过结构体中的指针连接成链表
struct st { unsigned char int1; unsigned char int2; unsigned char int3; struct st far * pst; }; main() { struct st starray[375]; int ii,sum; struct st far * pHead = 0; struct st far * pNow = 0; /*copy*/ for (ii=0; ii<375; ii++) { starray[ii] = *((struct st *)(0 + ii * sizeof(struct st))); } /*count*/ for (ii=0; ii<375; ii++) { sum = starray[ii].int1 + starray[ii].int2 + starray[ii].int3; if (sum < 400 && sum > 200) { if (pNow == 0) { pHead = &(starray[ii]); pNow = pHead; } else { pNow->pst = &(starray[ii]); pNow = pNow->pst; } } } pNow->pst = 0; /*output*/ pNow = pHead; sum = 0; while (pNow) { printf("int1 = %d,/tint2 = %d,/tint3 = %d,/tintSum = %d,/tpNext = %x%x/n",pNow->int1, pNow->int2,pNow->int3,pNow->int1+pNow->int2+pNow->int3,pNow->pst); pNow = pNow->pst; sum ++; if (sum > 10) { printf("----------------------------------------------------------------------------/n"); getch(); sum = 0; } } }
本文通过三个实例深入探讨了C语言中指针与结构体的应用:递归访问指针指向的数据;打印结构体地址及各成员的地址;从内存中选择符合条件的结构体并构建链表。
1128

被折叠的 条评论
为什么被折叠?



