C語言結(jié)構(gòu)體指針的示例代碼
更新時(shí)間:2025年07月14日 08:23:23 作者:暗影~行星
本文主要介紹了C語言結(jié)構(gòu)體指針的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
案例一:
#include <stdio.h>
#include <stdbool.h>
#include <string.h> // 添加string.h頭文件用于strcpy
//結(jié)構(gòu)體指針
//方式 1 : 先定義結(jié)構(gòu)體
struct Dog
{
char *name;
int age;
char weight;
};
//方式 1 :
char *get_dog_info(struct Dog dog)
{
static char info[40];
sprintf(info, "name:%s, age:%d, weight:%d", dog.name, dog.age, dog.weight);
return info;
};
char *get_dog_info1(struct Dog *dog)
{
static char info1[30];//靜態(tài)局部指針變量
sprintf(info1, "name:%s, age:%d, weight:%d", dog->name, dog->age, dog->weight);
return info1;
};
int main()
{
//方式1
struct Dog dog = {"旺財(cái)", 2, 10};
printf("dog info: %s\n", get_dog_info(dog));
//方式2
struct Dog *dog1 = &dog;
//或
char *Info = NULL;
Info = get_dog_info1(dog1);
printf("dog1 info: %s\n", Info);
printf("dog1 info: %s\n", get_dog_info1(dog1));
return 0;
}
案例二:
#include <stdio.h>
#include <stdbool.h>
#include <string.h> // 添加string.h頭文件用于strcpy
//結(jié)構(gòu)體指針
//方式 1 : 先定義結(jié)構(gòu)體
struct Box
{
double length;
double width;
double height;
};
double bulk(struct Box *box)
{
return box->length * box->width * box->height; //使用結(jié)構(gòu)體指針訪問結(jié)構(gòu)體成員
}
int main()
{
//方式1
struct Box box1;
printf("請輸入長、寬、高:\n");
scanf("%lf %lf %lf", &box1.length, &box1.width, &box1.height);
printf("體積 = %.2lf\n", bulk(&box1)); //使用結(jié)構(gòu)體指針作為函數(shù)參數(shù)
return 0;
}
案例三:
#include <stdio.h>
#include <stdbool.h>
#include <string.h> // 添加string.h頭文件用于strcpy
//結(jié)構(gòu)體指針
//方式2 : 在函數(shù)中定義結(jié)構(gòu)體
struct Person
{
char name[20];
int age;
double pay;
};
void print(struct Person *ptr)
{
// printf("姓名:%s,年齡:%d,工資:%.2lf\n", p->name, p->age, p->pay); //使用結(jié)構(gòu)體指針訪問結(jié)構(gòu)體成員
ptr->pay =( ptr->age > 18) ? 3000 : 1000;
}
int main()
{
//方式2
struct Person ptr11;
printf("請輸入姓名、年齡\n");
scanf("%s %d", &ptr11.name, &ptr11.age);
print(&ptr11);
struct Person *ptr = &ptr11;
printf("姓名:%s ,年齡:%d ,工資:%.2lf \n", ptr->name, ptr->age, ptr->pay); //使用結(jié)構(gòu)體指針訪問結(jié)構(gòu)體成員
return 0;
}
到此這篇關(guān)于C語言結(jié)構(gòu)體指針的示例代碼的文章就介紹到這了,更多相關(guān)C語言結(jié)構(gòu)體指針內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言使用posix正則表達(dá)式庫的實(shí)現(xiàn)
在C語言中,你可以使用 POSIX 正則表達(dá)式庫(regex.h)來進(jìn)行正則表達(dá)式的模式匹配,本文主要介紹了C語言使用posix正則表達(dá)式庫的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12
CreateCompatibleDC()函數(shù)案例詳解
這篇文章主要介紹了CreateCompatibleDC()函數(shù)案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C語言數(shù)據(jù)結(jié)構(gòu)堆的基本操作實(shí)現(xiàn)
這篇文章主要為大家介紹了C語言數(shù)據(jù)結(jié)構(gòu)堆的基本操作實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-11-11

