C语言中结构体的指针赋值

Silenceboyyu 2009-05-07 10:30:55
#include<stdio.h>
#include<malloc.h>
struct structure{
int m;
int n,p,q;
};
void main()
{
struct structure p;
p1={1,2,3,4};
printf("%d %d %d %d \n",p.m,p.n,p.p,p.q); //此处显示错误 syntax error : '{'
struct structure p1={1,2,3,4};
printf("%d %d %d %d \n",p1.m,p1.n,p1.p,p1.q);
struct structure *p2=(struct structure *)malloc(sizeof(struct structure));
*p2={1,2,3,4}; //此处显示错误 syntax error : '{'
printf("%d %d %d %d \n",p2.m,p2.n,p2.p,p2.q);
}
问题:在C中结构体只能赋初值吗?为什么会出现这种错误呢?
结构体中只能这样p1.m=1;p1.n=2;p1.p;p1.q=4;或p2->m=1;p2->n=1;p2->p=1;p2->q=1;或给各个成员赋值吗?不赋初值,先定义变量,再整体赋值不行吗?





...全文
356 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
WalterLee 2010-04-18
  • 打赏
  • 举报
回复
那这个怎么赋初值??
struct structure *p2=(struct structure *)malloc(sizeof(struct structure));
Silenceboyyu 2009-05-07
  • 打赏
  • 举报
回复
好,谢谢了
lhy 2009-05-07
  • 打赏
  • 举报
回复
2楼不是说了,这种赋值只能在初始化时用。
情况2是在初始化,情况1、3不是初始化。
Silenceboyyu 2009-05-07
  • 打赏
  • 举报
回复
谢谢了,是我打错了
情况1:
struct structure p;
p={1,2,3,4}; //此处显示错误 syntax error : '{'
printf("%d %d %d %d \n",p.m,p.n,p.p,p.q);
情况2:
struct structure p1={1,2,3,4};
printf("%d %d %d %d \n",p1.m,p1.n,p1.p,p1.q);
情况3:
struct structure *p2=(struct structure *)malloc(sizeof(struct structure));
*p2={1,2,3,4}; //此处显示错误 syntax error : '{'
printf("%d %d %d %d \n",p2.m,p2.n,p2.p,p2.q);
貌似情况1跟情况3都是错误的定义方法,但是这种定义为什么错呢?不符合C/C++中的语言规范吗?
yyunffu 2009-05-07
  • 打赏
  • 举报
回复
struct structure p ={1,2,3,4};
这种操作只能在定义的时候初始化。
rotus 2009-05-07
  • 打赏
  • 举报
回复
楼主代码有问题。

一般情况下
struct structure p ={1,2,3,4};
struct structure p1 = p;

或者成员分别赋值。


有其他的应用场景么?

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧