본문 바로가기

C언어

11월 29일 C언어 구조체

-구조체-

구조체는 사용자 정의 자료형이다.

먼저 #define test 1 이라고 쓰는데
#define
\test 1  
원래는 안되는 문장이지만 \(역슬래쉬)를 붙이면 연결된 문장으로 인식한다.

ex)
struct scb  // new type 이며 c++에서는 Class
{
int A; // old type 이다
};

class 안에는 함수도 넣을 수가 있다.
class scb  A 는 앞의 class를 생략하고 scb A 와같다.
여기서 A를 객체(메모리에 실제 존재해야)라고 하며 객체 지향 프로그래밍을(Object Oriented Programing)
OOP라도 한다. C 는 구조적 프로그램이다.
C에서는 함수 포인터를 사용하여 구조체 안에 함수를 넣는 효과를 낼 수 있는데, C로 객체지향흉내를 내는것이 OOC 이다. 안되는것을 억지로 구현하려고 하여 난해하다. (iPhone)

구조체를 편하게 쓰려고 typedef를 한다.
예를들어
typedef struct _scb{int A;}; SCB;
올드 타입은 잘은쓰는 _를 사용하고 뉴타입은 잘 쓰는것으로 적는다.

예제소스
주소, 문자, 크기를 넘겨주면 메모리를 문자로 채우는 함수 직접 구현(리눅스에 memset  함수가있다)

#include <stdio.h>

typedef unsigned char uchar;

struct scb
{
  int A;
  char B;
  int C;
};
void PrintSCB(struct scb *);
void my_memset(void *,unsigned char,int);

int main()
{
  struct scb A={1,'A',2};
  PrintSCB(&A);
  
  my_memset(&A,0,sizeof(struct scb));
  
  PrintSCB(&A);
  
  printf("address of A  : %08X\n",&A);
  printf("address of A.A: %08X\n",&A.A);
  printf("address of A.B: %08X\n",&A.B);
  printf("address of A.C: %08X\n",&A.C);
  return 0;
}

void PrintSCB(struct scb *stData)
{
  printf("%d\n",stData->A);
  printf("%d\n",stData->B);
  printf("%d\n",stData->C);
}
void my_memset(void *vAdd,uchar ucVal,int iSize)
{
  while(iSize>0)
  {
  --iSize;
  *((uchar *)vAdd+iSize)=ucVal;
  }
  
}