본문 바로가기
공부,일/c언어

구조체

by fromnothing1 2021. 6. 3.
#include<stdio.h>

struct test;
	
int main()
{
	// 구조체 선언과 초기화 

	struct test  // test  구조체를 선언 하고 동시에 초기화 
	{
		char name[20];
		int kor, eng, math;
		float avg;
	}scoer_data = {"kim",80,90,75,81.66 };

	struct test2 
	{
		char* name; // 포인터 선언
		int kor, eng, math;
		float avg;
	};

	//구조체 배열 초기화 

	//  개별로 입력 받기 

	struct test score;
	strcpy(score.name, "kim");
	//socer.name = "kim"; socer.name 은 배열임으로 주소를 받을 수는 없다. 1

	score.kor = 1;
	score.eng = 2;
	score.math = 3;
	score.avg = 1.1;

	printf("score.name : %s\n", score.name);
	printf("score.kor : %d\n", score.kor);
	printf("score.eng : %d\n", score.kor);
	printf("score.math : %d\n", score.kor);
	printf("score.avg : %d\n", score.kor);

	printf("sizeof(struct test) : %d\n",sizeof(struct test)); //4+4+4+4+20 = 36
	printf("sizeof(score) : %d\n", sizeof(score));

	struct test sd_arr[10]; // 구조체 배열 선언 




	struct test2 *sp;// 구조체 포인터 선언
	struct test2 sd;
	sp = &sd;

	(*sp).name = "kim";
	printf("sd.name : %s\n", sd.name);

	//주소값+ 구조체 = -> 기호를 제공한다. 
	printf("\n-> 기호 사용 \n\n");
	sp->name = "asdf";
	printf("sp->name %s\n", sp->name);


	//구조체 복사 같은 구제체이면 그냥 복사 할수 있다.
	printf("\n score 복사  \n\n");
	struct  test  score2;
	
	score2 = score;

	printf("score2.name : %s\n", score2.name);
	printf("score2.kor : %d\n",  score2.kor);
	printf("score2.eng : %d\n",  score2.kor);
	printf("score2.math : %d\n", score2.kor);
	printf("score2.avg : %d\n",  score2.kor);

	return 0;

}

 

구조체 배열과 구조체 주소이동 

#include<stdio.h>

struct test;
	
int main()
{
	// 구조체 선언과 초기화 

	struct test  // test  구조체를 선언 하고 동시에 초기화 
	{
		char name[20];
		int kor;
	};


	struct test sd_arr[3] =
	{
		{"aaa",1},
		{"bbb",2},
		{"ccc",3}

	};
	struct  test* p;

	p = sd_arr; 

	printf("p[0].name : %s\n", p[0].name);
	printf("p[1].name : %s\n", p[1].name);
	printf("p[2].name : %s\n", p[2].name);
	printf("sd_arr[0].name : %s\n", sd_arr[0].name);
	printf("sd_arr[1].name : %s\n", sd_arr[1].name);
	printf("sd_arr[2].name : %s\n", sd_arr[2].name);

					  
	printf("(*p).name   : %s\n", (*p).name);
	printf("(*p).name   : %s\n", (*(p+1)).name);
	printf("(*p).name   : %s\n", (*(p + 2)).name);
	printf("(p)->name   : %s\n", (p)->name);
	printf("(p+1)->name : %s\n", (p+1)->name);
	printf("(p+2)->name : %s\n", (p+2)->name);


	// 주소는 조금 이해 못하겠네 
	printf("p        : %p\n", p);
	printf("p+1      : %p\n", p+1);
	printf("sd_arr) : %p\n", sd_arr);
	printf("sd_arr[0]: %p\n", sd_arr[0]);
	printf("sd_arr[1]: %p\n", sd_arr[1]);


	return 0;

}

'공부,일 > c언어' 카테고리의 다른 글

공용체  (0) 2021.06.04
비트필드  (0) 2021.06.03
함수포인터  (0) 2021.06.02
sizeof 와 포인터 & 배열의 data type  (0) 2021.06.01
void pointer , malloc  (0) 2021.06.01

댓글