- 论坛徽章:
- 0
|
在学习C的struct的时候,写了这么一段程序:
- 1 #include<stdio.h>
- 2 #include<string.h>
- 3
- 4
- 5 typedef struct b{
- 6 char*b;
- 7 }b;
- 8
- 9 typedef struct c{
- 10 b*structb;
- 11 }c;
- 12
- 13
- 14 int
- 15 main()
- 16 {
- 17 char buffer[265];
- 18 char*tmp;
- 19 char*chap;
- 20 printf("input chap:");
- 21 tmp=fgets(buffer,256,stdin);
- 22 strcpy(chap,tmp);
- 23 int*i=0;
- 24 struct c *tmpc;
- 25 printf("input b:");
- 26 tmp=fgets(buffer,256,stdin);
- 27 strcpy(tmpc->structb->b,tmp);
- 28 printf("%s",tmpc->structb->b);
- 29 printf("%s",chap);
- 30 }
复制代码
编译通过没问题,问题是在运行的时候出现"Bus error"的提示。
于是我改了第22行和27行的代码如下:
修改《一》
- 22 chap=tmp;
- 27 tmpc->structb->b=tmp;
复制代码
或者这样:
修改《二》
- 21 chap=fgets(buffer,256,stdin);
- 25 tmpc->structb->b=fgets(buffer,256,stdin);
复制代码
编译运行都没有问题,但是又出现这样的结果:
input chap:fdf
input b:sd
sd
sd
让我非常的不理解,为什么分别赋值过了,b和chap的结果还是一样的呢?
难道我这样做了只是把b和chap指向了tmp的地址?如果我想要分别给这两个指针指向的地址赋值。
还有一个问题就是,如果我在声名struct b或者struct c的时候,如果写成这样:
- 5 typedef struct b{
- 6 char*b;
- 7 };
- 8
- 9 typedef struct c{
- 10 b*structb;
- 11 };
复制代码
在编译的时候会报错,这两种写法紧紧是在最后少了一个struct自己的名字而已,就会有这么大的不同。这两种写法有什么区别呢?
谢谢! |
|