结构体数组的C程序用指针输出时,为什么只输出一个字符,请看我的源程序,很短:

来源:百度知道 编辑:UC知道 时间:2024/05/20 23:37:34
#include <stdio.h>

struct {
int x;
char *y;}tab[2]={{1,"ab"},{2,"cd"}},*p=tab;
void main()
{printf("%s and %s.\n",*(++p)->y,*p->y);/*改成%c and %c时,输出c和a,可是%s and %s,越界错误,我用了指针,指针不是指向“ab"这个字符数组吗,输出时为什么就只能输出一个字符,怎样改才能输出两个字符?谢谢*/
getch();
}

p->y是"cd"的首元素'c'的地址,前面加个*以后就是'c'
%s的话,需要的是一个字符串的首地址,但是你给的参数*p->y是个字符

printf("%s and %s.\n",(++p)->y,p->y);

printf("%s and %s.\n",*(++p)->y,*p->y);
在->的左边是地址值,改为 printf("%s and %s\n",p->y,(p+1)->y);就可以了。

printf("%s and %s.\n",*(++p)->y,*p->y);改为:
printf("%s and %s.\n",(p++)->y,p->y);