C

구조체 포인터

NationCore 2019. 3. 6. 22:43


// 변수 구조 선언

typedef struct{

char title[50];

char address[50];

int s_num;

}univ;



void main(void)

{

univ sku = { "성공대학교","서울시",2000 };

univ *ptr = &sku; // 포인터에 주소 할당


printf("학교: %s 주소: %s 학생 수: %d \n", ptr->title, ptr->address, ptr->s_num); 

// 포인터가 가르키는 구조체 멤버


printf("학교: %s 주소: %s 학생 수: %d \n",(*ptr).title,(*ptr).address,(*ptr).s_num); 

//  포인터가 가르키는 구조체 멤버


printf("학교: %s 주소: %s 학생 수: %d \n", sku.title, sku.address, sku.s_num); 

// 구조체 데이터 불러들이기

}



결과 :







그 구조체가 배열일 경우




void main(void)

{

  univ sku[3] = { { "성공대학교","서울시",2000 },{"성남대학교","부천시",32000},{"자녀대학교","군산시",16000} }; 

univ *ptr = &sku;


for (int i = 0; i < 3; i++) {

printf("학교: %s 주소: %s 학생 수: %d \n", (ptr + i)->title, (ptr + i)->address, (ptr + i)->s_num);

printf("학교: %s 주소: %s 학생 수: %d \n", (*(ptr + i)).title, (*(ptr + i)).address, (*(ptr + i)).s_num);

}

}



결과 : 





다중 포인터의 경우




void main(void)

{

univ sku[3] = { { "성공대학교","서울시",2000 },{"성남대학교","부천시",32000},{"자녀대학교","군산시",16000} };

univ *ptr = &sku;

univ **ptr2 = &ptr;


for (int i = 0; i < 3; i++) {

printf("학교: %s 주소: %s 학생 수: %d \n", (ptr + i)->title, (ptr + i)->address, (ptr + i)->s_num);

printf("학교: %s 주소: %s 학생 수: %d \n", (*(ptr + i)).title, (*(ptr + i)).address, (*(ptr + i)).s_num);

}


printf("\n다중 포인터 경우 : \n");

for (int j = 0; j < 3; j++) {

printf("학교: %s 주소: %s 학생 수: %d \n", (*ptr2 + j)->title, (*ptr2 + j)->address, (*ptr2 + j)->s_num);

printf("학교: %s 주소: %s 학생 수: %d \n", (*(*(ptr2 )+j)).title, (*(*(ptr2)+j)).address, (*(*(ptr2)+j)).s_num);

}

}



결과 :







//구조체 포인터로 선언


#include <stdio.h>


void main(void){


struct 

{

int i;

float f;

} s, *ps; // 포인터 구조체, 구조체 두개 선언


ps = &s; // 포인터 구조체에 구조체 주소를 대입

ps->i = 2;

ps->f = 3.14;


printf("%f %d \n",ps->f,ps->i);

printf("%f %d \n",s.f,s.i);

}



결과 :