学习C的历程(七)

通过指针给结构体成员赋值的方式

#include <stdio.h>
#include <stdlib.h>

struct FF{
    int a;
    int b;
};
int main()
{
   struct FF* t;
   t=(struct FF*)malloc(sizeof(struct FF));
   t->a=3;
   t->b=4;
   
   
   printf("%d",(t->a));
   free(t);
   
   return(0);
}

==============================================================================

#include <stdio.h>
#include <stdlib.h>
int main()
{
   struct FF{
       int *m;
       int a;
   };
   struct FF* ff;
   
   ff=(struct FF*)malloc(sizeof(struct FF));
   int x=9;
   /*注意这里如果直接未经强制类型转换就把ff->m(指针)赋值为一个整数,编译结果会出现警告*/
   ff->m=&x;                            
   ff->a=3;
   printf("%d\n",*(ff->m));
   printf("%d",ff->a);
   return 0;
}

结构体成员中如有指针类型则必须指向有效内存

#include <stdio.h>
#include <string.h>
#include <stdlib.h> 
struct dog{
     char *name;
     int  weight;
     char *color;
 };
 
void display(struct dog *n);

int main()
{
  
 
 struct dog m;
 
 /*
 下面两行缺一不可,
 如果不想要这两行可以把
 结构体改为 struct dog{
     char name[100];
     int  weight;
     char color[100];
 };
 */
 m.name=(char*)malloc(200*sizeof(char));
 m.color=(char*)malloc(200*sizeof(char));
 
 
 m.weight=30;
 strcpy(m.name,"ahuang");
 strcpy(m.color,"yellow");
 display(&m);
 
   return 0;
}

void  display(struct dog *n){
     printf("%s is %d and it is %s",n->name,n->weight,n->color);
 }

函数指针

#include <stdio.h>

 int max(int x){return x;}
 
  int main(){
  int (*prt)(int)=max;//第一个括号必须写
  printf("%d",prt(10));//或者写成printf("%d",(*prt)(10))也行
    return 0;
}

非strcpy的赋值方式

#include <stdio.h>
#define LEN 30
 struct person{
       char *f;
       char *m;
       int n;
   };
int main()
{
   struct person son;
   char str[LEN]="xiaolan";
   char st[LEN]="xiaoming";
   son.f=str;
   son.m=st;
   son.n=45;
   printf("%s %s %d",son.f,son.m,son.n);
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值