코딩/C언어

수업026_구조체

tree0505 2025. 7. 11. 11:49
반응형
    • _21_교재

  • 수업026_구조체.cpp
#include <stdio.h>
#include <stdlib.h>

//struct는 자바로 치면 class와 같다. 
    //class a{
        //}
    //A a = new A(); 
    //A b; //비여있는것 


struct person{
    char* name; 
    int age;
    //밑에서 생기라는 요청이 있어서. name과 age가 생김 
};

//struct person p; //이것이 자료형 //들어있다. new를 안해도. 

int main(void) {
    // 구조체 pass
    struct person u1; //1번에 u1이 생기고 
    //위에서 new를 해서 이것이 생김    
        //char* name;
        //int age;

    u1.name = "A"; //3번째 영역에 string에 생김 
    u1.age = 30;
    printf("%s %d\n" , u1.name , u1.age);
    	
    struct person u2;
    u2.name = "B";
    u2.age = 40;
	struct person* p;
	p = &u2;
    //p[0].name, p[0].age
    //(*p).name, (*p).age
    //축약형 . p->name , p->age

	printf("%s %d\n" , p->name , p->age);

	return 0;
}

  • 메모리 


  • _21_문제

  • 문제026_구조체.cpp
#include <stdio.h>
#include <stdlib.h>

struct person{
    char* name;
    int age;
};

int main(void) {
    // 구조체 pass

    struct person u1;
    u1.name = "A";
    u1.age = 30;
    printf("%s %d\n" , u1.name , u1.age);
    	
    struct person u2;
    u2.name = "B";
    u2.age = 40;
	struct person* p;
	p = &u2;
	printf("%s %d\n" , p->name , p->age);

	return 0;
}

 


  • 문제026_구조체02.cpp
#include <stdio.h>
#include <stdlib.h>

/*struct test{
    int * ptest;
}
*/
int main(void) {
    //struct test data;
    //struct test* p;
    //data = &p;
    
    // 밑에꺼는. 위의 주석을 한줄로 만든것 
    struct list{

        int * pt;

    }data, *p; //변수가 2개가 있는것 
    
    int x[] = {100, 200, 300, 400};
    p = &data; //같다.    data = &p; //주소를 준것 
    p->pt = x + 1; //200의 주소가 들어간것. y5주소 
    printf("%d" , *(++p->pt));
    printf("%d" , *(++(p->pt)));
    //p -> pt 
    //y5 ++를 한것 => y9가 된다. //그거의 값 300 

	return 0;
}

  • 메모리 


  • 문제026_구조체03.cpp
#include <stdio.h>
#include <stdlib.h>

struct person
{
    char name[10];
    int age;
};


int main(void) {
    struct person s[] = 
    {"Kim" , 28, "Lee" , 38 , "Seo" , 50 , "Park" , 35};
    struct person *p;
    p = s; //축약 &s[0] //k의 주소가 있다. 
    p ++; //L
    printf("%s\n" , p->name); //Lee
    printf("%d\n" , p->age); //38 
	return 0;
}

  • 문제026_구조체04.cpp
#include <stdio.h>
#include <stdlib.h>

struct jsu
{
    char name[12];
    int os, db, hab, hhab; 
};


int main(void) {
    struct jsu st[3] = {
    	{"데이터1", 10, 20}, // 0, 0 생략됨 
		{"데이터2", 30, 40}, // 0, 0 생략됨 
		{"데이터3", 50, 60}, // 0, 0 생략됨 
	}; 
    
    struct jsu* p;
	p = &st[0]; //p = st; //'데' 의 주소를 가지고 있다. 
	
	(p + 1)->hab = (p + 1)->os + (p + 2)->db;
	//(p + 1)->hab => 데이터 2의 첫번째 0 
	//(p + 1)->os => 30 
	//(p + 2)->db => 60 
	// 90 

	(p + 1)->hhab = (p + 1)->hab + p->os + p->db;
	//(p + 1)->hhab => {"데이터2", 30, 40}, //데이터 2의 두번째 0
	//(p + 1)->hab => 90 
	//p->os => 10 
	//p->db => 20 
	//120 

	printf("%d \n" , (p + 1)->hab ); // 90 

	printf("%d \n" , (p + 1)->hhab);  //120
    
	return 0;
}
반응형