结构体指针

结构体指针

# include //引用函数库
# include 
struct info{
    char name[4];
    int age;
};
void main(){
    struct info student1;
    student1.age = 19;
    sprintf(student1.name,"li");
    printf("%d,%s\n",student1.age,student1.name);

    struct info *p;//p存储地址,struct info决定内存长度
    p=&student1;
    printf("%d,%s\n",(*p).age,(*p).name);//指针访问结构体第一种方法
    printf("%d,%s\n",p->age,p->name);//指针访问结构体第二种方法
}

结构体数组指针

# include //引用函数库
# include 
struct info{
    char name[10];
    int age;
};
void main(){
    struct info student1[2]={"li",18,"lu",17};
    for (struct info *p =student1;p2;p++){
        printf("%s,%d\n",p->name,p->age);
        printf("%s,%d\n",(*p).name,(*p).age);
    }
}

结构体指针作为参数

# include //引用函数库
# include 
struct info{
    char name[10];
    int age;
};
change(struct info *p){
    p->age=10;
}
void main(){
    struct info student1={"li",18};
    change(&student1);
    printf("%d",student1.age);
}

结构体数组作为参数

# include //引用函数库
# include 
struct info{
    char name[10];
    int age;
};
change(struct info student[]){//函数参数传递的是数组的地址,而不是新建了一个数组
    student[1].age=100;
}
void main(){
    struct info student1[2]={"li",18,"lu",17};
    change(&student1);
    printf("%d",student1[1].age);
}

动态分配结构体内存

# include //引用函数库
# include 
struct info{
    char name[10];
    int age;
};
void main(){
    struct info *p=(struct info *)malloc(sizeof(struct info)*2);//malloc返回的是void类型指针,所以要强转
    for (int i =0;i<2;i++){//指针数组
        p[i].age=i*10;
        printf("%d ",p[i].age);
    }
    for (int i =0;i<2;i++){//指针
        (*(p+i)).age=i*10;
        printf("%d ",(*(p+i)).age);
    }
    for (struct info *pp=p;pp2;pp++){//指针轮循
        (*pp).age=10;
        printf("%d ",(*pp).age);
    }
}

你可能感兴趣的:(c-c++)