구조체는 연관있는 데이터를 하나의 그룹으로 믂기위해서 등장하였다.


C++에서도 구조체를 선언할수있다.


struct Smartphone Samsung;

struct Smartphone Apple;


이와 같이 선언이 가능하다. struct 키워드는 typefed를 통해서 축약이 가능하다.

예를들자면,


#include <iostream>


#define  LEN  30


using namespace std;



struct Smartphone 

{

char phonename[LEN]; //핸드폰 이름

int version;

int price; 

}


void showphone(const Smartphone  &phone)

{

cout<<"핸드폰명:"<<phone.phonename<<endl;

cout<<"버전명:"<<phone.version<<endl;

cout<<"현재가격:"<<phone.price<<"dollar"<<endl<<endl<<;


}


int main(void)

{

Smartphone apple={"apple, 2, 800}

showphone(apple);


}


매우 간략한 예제이지만, 구조체의 사용법과 간단히 함수의 동작에 대해서 이해가 가능할것으로 보인다.

여기서 하나의 의문을 가질수가 있다.

만약 구조체안에다가 함수를 삽입하면 어떻게 될까??





#include <iostream>


#define  LEN  30


using namespace std;



struct Smartphone 

{

char phonename[LEN]; //핸드폰 이름

int version;

int price; 


void showphone() //매개변수는 불필요 해졌다.

{

cout<<"핸드폰명:"<<phonename<<endl; //연산의 대상에 대해서 정보가 불필요해졌다.

cout<<"버전명:"<<version<<endl;      //변수에 대한 직접접근이 가능하기 떄문이다.

cout<<"현재가격:"<<price<<"dollar"<<endl<<endl<<;


}


}


int main(void)

{

Smartphone apple={"apple", 2, 800}

apple.showphone(apple);

return 0;

}



이로써 구조체는 대충 이해가 되었다. 그렇다면, 클래스와 구조체의 차이점은 무엇일까??


> 선언법과 초기화법이 다르다.

> 클래스의 변수와 함수에 대한 접근법이 다르다.  (접근제어 지시자의 사용)





* 접근제어 지시자


C++에서 접근제어 지시자는 아래와같이 3가지의 형태가 존재한다.


1) public : 어디서든 접근허용

2) protected : 상속관계에 놓여있을 때, 유도 클래스에서의 접근허용

3) private : 클래스 내 (클래스 내에 정의된 함수)에서만 접근허용


먼저 1)과 3)번에 관해서 아래의 예를 통하여 이해해 보자.


#include <iostream>



#define  LEN  30


using namespace std;



class Smartphone 

{


private:

char phonename[LEN]; //핸드폰 이름

int version;

int price; 

public:

void initphone(char *ID, int v, int p);

void showphone();

}


void Smartphone::initphone(char *NAME, int v, int p)

{

strcpy(phonename, NAME);  //phonename공간에 NAME의 내용을 복사한다.

version = v;

price = p;

}


void Smartphone::showphone() //매개변수는 불필요 해졌다.

{

cout<<"핸드폰명:"<<phonename<<endl; //연산의 대상에 대해서 정보가 불필요해졌다.

cout<<"버전명:"<<version<<endl;      //변수에 대한 직접접근이 가능하기 떄문이다.

cout<<"현재가격:"<<price<<"dollar"<<endl<<endl<<;


}



int main(void)

{

Smartphone apple;

apple.initphone("apple", 2, 800);

apple.showphone(apple);

return 0;

}


private 과 public의 쓰임을 이해하기 위해서 위의 예제를 먼저 따라가보자.

Smartphone 이라는 클래스가 선언되었고, 클래스는 private 과 public으로 구분된다.

public은 어디서든 접근이 가능하며, private 는 해당하는 범위 내에서만 접근이 가능하다.


따라서 위의 예제에서는 private 으로 접근을 하기 위해서 같은 클래스내에 public으로 선언된 initphone 함수를 통해서

초기화를 수행한다. 왜냐하면 private으로 변수나 함수가 선언되면 main함수에서 직접적으로 접근이 불가능하기 떄문이다. 

따라서 public으로 선언된 함수를 통하여 같은 클래스내의 private으로 접근하여 초기화를 수행한다. 


구조체의 경우는 Private이 없다. 기본적으로 구조체는 모든 변수와 함수는 public으로 선언되었다고 생각하면 된다.

만약 클래스에서 접근제어 지시자를 쓰지 않으면 구조체와는 반대로 모두 private으로 선언되었다고 봐야한다.


[용어의 정리]


위에서 말한 변수는 "객체"라고 표현된다.

클래스를 구성하는 변수는 "멤버변수"라고 부르며,

클래스를 구성하는 함수는 "멤버함수"라고 부란다.


그리고 C++에서는 H(헤더파일), CPP(정의파일) 로 코드들이 구분되어 다루어진다.


예를들어, 

Smartphone.h    : 클래스의 선언을 담는다

Smartphone.cpp : 클래스의 정의(멤버함수의 정의)를 담든다.


따라서, 위의 예제를 파일로 나눠본다면 아래와 같이 된다.


[Smartphone.h]


#ifndef __SMARTPHONE.H__

#define __SMARTPHONE.H__


#define  LEN  30


class Smartphone 

{


private:

char phonename[LEN]; //핸드폰 이름

int version;

int price; 

public:

void initphone(char *ID, int v, int p);

void showphone();

}



[Smartphone.cpp]


#include <iostream>

#include "Smartphone.h"


using namespace std;

void Smartphone::initphone(char *NAME, int v, int p)

{

strcpy(phonename, NAME);  //phonename공간에 NAME의 내용을 복사한다.

version = v;

price = p;

}


void Smartphone::showphone() //매개변수는 불필요 해졌다.

{

cout<<"핸드폰명:"<<phonename<<endl; //연산의 대상에 대해서 정보가 불필요해졌다.

cout<<"버전명:"<<version<<endl;      //변수에 대한 직접접근이 가능하기 떄문이다.

cout<<"현재가격:"<<price<<"dollar"<<endl<<endl<<;


}



[applephoneMain.cpp]


#include "Smartphone.h"


int main(void)

{

Smartphone apple;

apple.initphone("apple", 2, 800);

apple.showphone(apple);

return 0;

}














when it comes to

~에 관한 한



on the one hand

한편으로는


cope with

 

…에 대처[대응]하다; …에 대항하다. 



in[to] excess


~ 극단적으로



get through 


+to 어디 : ~에 진출하다.  

(~에게) 가 닿다[전달되다]


+ Something : ~을 많이 써버리다.


+ to Someone : ~누그를 이해, 납득시키다



give rise to something


(격식) ~이 생기게 하다

The novel's success gave rise to a number of sequels.

그 소설의 성공으로 몇 권의 속편이 나왔다.



belong to somebody


~ 소유[것]이다, ~에 속하다

Who does this watch belong to?

이 시계 누구 거죠?

The islands belong to Spain.

그 섬들은 스페인에 속한다.


~ 차지[세상]이다

British actors did well at the award ceremonybut the evening belonged to the Americans.예문 발음듣기

시상식에서는 영국 배우들이 잘 했지만 그날 저녁은 미국 배우들 세상이었다.




by means of something



(격식) ~의 도움으로[~을 써서]

The load was lifted by means of a crane.

그 짐은 기중기를 써서 들어올렸다.



the fact (of the matter) is (that)…



(특히 방금 언급된 내용과 반대됨을 강조하여) 사실은 …이다

A new car would be wonderful but the fact of the matter is that we can't afford one

새 차라면 멋지겠지. 하지만 사실은 우리가 그럴 형편이 안 돼.



point out (to somebody)


(주의를 기울이도록 ~을) 지적[언급]하다 동의어 point something out (to somebody)

She tried in vain to point out to him the unfairness of his actions.

그녀는 그에게 그의 행동의 부당함을 지적하려 했으나 허사였다.

He pointed out the dangers of driving alone.

그는 혼자 운전하는 것의 위험을 지적했다.

[+ that]I should point out that not one of these paintings is original.

이 그림들 중 어느 것도 원본이 아니라는 것을 제가 언급해야겠군요.


ana·logy

 


명사(pl. -ies)

1.[C] ~ (between A and B) | ~ (with sth) 비유; 유사점

The teacher drew an analogy between the human heart and a pump.예문 발음듣기

선생님은 인간의 심장을 펌프에 비유했다.

There are no analogies with any previous legal cases.예문 발음듣기

이전에 있은 어떤 법률 소송과도 유사점이 없다.



프로그램의 실행시 메모리의 구조는 OS를 가진 PC의 경우 아래와 같이 4가지 형태로 구성된다.


1)코드영역


2)데이터영역


3)힙영역 FIFO


4)스택영역 LIFO


갑자기, 옛날이야기를좀 하자면,

내가 C언어를 직관적으로 이해하게 되었고, 관심을 가지게 된것은 MCU를 다루면서 부터이다.

MCU를 장난감처럼 다루기 위해서는 입력과 조작의 도구로써, 프로그래밍 언어는 필수였었다.

물론 처음에는 남들이 작성해놓은 코드를 그대로 복사해서 넣어보고 동작하는것을 보고 좋았지만..

후에 내가 원하는 시스템을 설계하기 위해서는 프로그래밍 코드의 작성과 이해없이는 절대 제어가 불가능 했었다.

그래서 하나씩 코드에 의문을 가지게 되었으며

특히, 윤성우님이 저술한 열혈 C프로그램밍이란 책은 매우 쉬운 이해가 가능하도록 도와주었다.


대학교라는 특수한 교육공간에서 전공에서 배우는 프로그래밍언어수업보다 스스로하는 자기학습이 더 많은 이해와

프로그래밍에 대한 직관력을 길러주었다. 머 그래서 학교의 주입식 교육을 비판하자는 것은 아니고..

암튼 다시 돌아가서 아래는 MCU에 주입하는 프로그램을 코딩할때 내가 자주 고민하던 문제들이다.

 [아트메가 시리즈를 사용했으며, Avr Studio라는 컴파일러를 사용헸을때의 경우이다.]


>현재 코딩하는 코드는 어디에 저장될까? (플래쉬메모리-응용프로그램 섹션) 라는 고민을 했었다.

>분명 MCU에서 제공하는 레퍼런스 메뉴얼의 커맨드들은 모두다 16진수의 메모리를 가지고 있던데..이들은 어디에 어떻게 선언이 되어있는걸까?..

>그럼 코드내에 선언되는 변수는 어디에 저장이 될까?  

 : 전역과 정적변수는 데이터영역

 : 지역과 매개변수는 스택영역-이곳에서도 생성과 소멸이 이루어짐

                                           지역변수도 중괄호가 끝나면 소멸되기에.

 : 프로그래머가 변수들의 생성과 소멸을 정하는 경우 힙영역

>MCU의 시동시에는 컴퓨터와 같이 부팅이 있을까??

 :  부트 프로그램 섹션.

>잠깐 잠깐 빠르게 연산되는 변수들과 처리는 어디에서 빠르게 처리되는걸까?

 : ALU 산술처리 연산장치, 이들의 처리된 결과값들은 상태 레지스터에 기록된다. 

   제대로 명령이 처리되었다면 프로그래머는 상태 레지스터의 값을 읽어서 맞는지 판단하면된다. (예를들면 If문을 확인)



이와 같이 각 선언되는 변수나 상수에 따라서 저장되는 메모리의 영역은 다르다. 왜냐하면 비슷한 성향의 데이터들을 묶어서 저장해놓으면 관리와 접근속도가 당연히 빠르기 때문이다. 


그래서, 대부분의 메모리할당은 전역변수와 지역변수, 즉 데이터영역과 스택영역으로 처리가 된다.

하지만 이들로 해결이 되지 않는 상황이 발생할수가 있다. 그래서 힙영역이 필요하다.

아래는 힙영역이 필요한 이유 이다.


[실패한 예제]

#include <stdio.h>



char * inputName(void)

{

char name[20];

printf("what is your name?");

gets(name);

return name;

}


int main(void)

{

char * name1;

char * name2;

name1 = inputName();

printf("name1 = %s \n", name1);

name2 = inputName();

printf("name2 = %s \n", name2);

return 0;

}


의 예제의 경우, 포인터로 구성된 함수와 변수들은 지역함수로 선언된 InputName 함수로 인하여

원하는 결과를 보여주지 못한다. 왜냐하면 지역변수로 선언된 함수는 종료후 변수값들이 소멸되기 때문이다.



따라서, 이를 해결하기위해선, 변수가 할당이 되면 전역변수와 마찬가지로 함수를 빠져나가도 소멸되지 않는 성격의 변수가 필요하다. => 이는 힙 영역의 메모리를 사용할 경우 해결이 가능하다. 

후에 C++로 넘어갈 경우 메모리 구조에 대한 직관적인 이해는 반드시 필요할 것이다. 미리미리 공부하자.


>힙영역의 메모리 공간할당과 해제는 malloc 와 free 함수로 할수 있다.


void * malloc(size_t size);  // 힙역역으로의 메모리 공간 할당

void free(void * ptr); // 힙 영역에 할당된 메모리의 공간해제


=> malloc함수는 성공 시 할당된 메모리의 주소값을 가지고, 실패시 NULL을 반환한다.

그래서 사람들은 흔히 힙 영역을 "프로그래머가 관리하는 메모리 공간"이라고 명명한다.


예시: 

int main(void)

{

void * pointer1 = malloc(sizeof(int));  // int형 크기로 힙영역에 할당된다.

//사실 위 코드의 의미는

// void * pointer1 = malloc(4); 와 같다. 이는 어떻게 사용할지는 사용자에게 달려있기 때문이다.  

// 따라서, 반환디는 주소값을 적절히 형 변환해서 할당된 메모리에 접근해야만 에러가 없다.


      free(pointer1);  //pointer1이 가리키는 4bytes의 메모리 공간이 해제 되었다.


}




이제 앞서 실패한 예제를 malloc 함수와 free를 사용해서 다시 해결해보자.


[해결된 예제]


#include <stdio.h>

#include <stdlib.h>


char * inputName(void)

{

char * name = (char *)malloc(sizeof(char)*20);  //힙영역에 메모리 할당

printf("what is your name?");

gets(name);

return name;

}


int main(void)

{

char * name1;

char * name2;

name1 = inputName();

printf("name1 = %s \n", name1);

name2 = inputName();

printf("name2 = %s \n", name2);

free(name1);

return 0;

}


따라서, malloc함수를 사용하게되면 지연변수나 전역변수로는 감당할수 없는 포인터관련 함수와 변수들로 일어나는 문제점들을 해결 할수가 있다. 



'Engineering > C Language' 카테고리의 다른 글

[C언어] 비트연산자와 16진법  (0) 2014.02.27
[C++] 구조체와 클래스  (0) 2014.02.24
[본문스크랩] enum의 사용법  (1) 2014.01.28
[C언어] 구조체사용하기  (0) 2014.01.16
[C언어] 포인터 사용하기-2  (0) 2014.01.15
연산속도 단위

 - ㎳(mili second) : 10-3초       천분의 1
 - ㎲(micro second) : 10-6초    백만분의 1
 - ㎱(nano second) : 10-9초     10억분의 1
 - ㎰(pico second) : 10-12초      1조분의 1
 - fs(femto second) : 10-15초    1000조분의 1
 - as(atto second) : 10-18

 

 

엑사(exa): 1018(100경), 기호: E
페타(peta): 1015(1000조), 기호: P
테라(tera): 1012(1조), 기호: T
기가(giga): 109(10억), 기호: G
메가(mega): 106(100만), 기호: M
킬로(kilo): 103(1000), 기호: k
                        헥토(hecto): 102(100), 기호: h
                        데카(deca): 101(10), 기호: da
------------------------------------------------

                        데시(deci): 10-1(10분의 1), 기호: d
                        센티(centi): 10-2(100분의 1), 기호: c

밀리(mili): 10-3(1000분의 1), 기호: m
마이크로(micro): 10-6(100만분의 1), 기호: μ(그리스 문자 뮤)
나노(nano): 10-9(10억분의 1), 기호: n
피코(pico): 10-12(1조분의 1), 기호: p
펨토(femto): 10-15(1000조분의 1), 기호: f
아토(ato): 10-18(100경분의 1), 기호: a



출처: http://blog.naver.com/dreplact/2000394783


'Any Notion > What is that?' 카테고리의 다른 글

[기호] 수학기호 특수기호 그리스기호 읽는법.  (0) 2014.10.06
AD-HOC network  (0) 2013.04.29
Daemon  (0) 2013.04.29
D-BUS  (0) 2013.04.29
Namespace in C++  (0) 2013.04.29

출처 :  네이버 지식인.


더블클릭후 보세요.




출처 :  네이버 지식in

http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=70600274&qb=ZW51bQ==&enc=utf8&section=kin&rank=3&search_sort=0&spq=1&pid=RXPJbc5Y7tGssckXvJNsssssstG-506114&sid=Uue7GHJvLB4AAHbuDW8


re: enum에 대해서..(내공有)

mydog21 
답변채택률73.2%
 
2008.01.09 14:43


쉽게 말해 enum 은 열거형 변수 입니다.

"어떻게" 생각하면 struct와 다르냐? 라고 물을 수 있지만.

"전혀" 다릅니다.

 

보통 enum은 상수를 정의하는데에 많이 쓰입니다.

소스의 가독성을 높인다거나 상수에 의미를 부여해서 쓸 수 있습니다.

 

전처리기인 #define 을 사용하거나, 전역 변수를 const로 선언해서 상수처럼 사용이 가능하지만

enum을 상수로 생각해서 처리할때의 이점이 있습니다. (뒷부분에 설명하겠습니다.)

 

우선 이넘(enum)을 선언하는 방법은 다음과 같습니다.

 

enum {mon, tue, wed, thr, fri, sat, sun } day;

 

여기서 day를 열거형 변수라 하고 그 하위의 항목(원소) 들 ( mon, tue, wed, thr, fri, sat, sun)로 구성됩니다.

 

특별하게 값을 지정하지 않는다면 enum의 각 원소들은 순차적인 "정수" 값을 갖게 됩니다.

이때 갖게되는 값은 mon부터 0, 1, 2 ... 6 까지 각 각 가지게 됩니다.

 

특별하게 값을 지정해서 enum을 사용한다면

 

enum {mon=100, tue, wed=200, thr, fri=300, sat, sun } day;

 

이렇게 선언을 하게 되면, mon은 당연히 100일거고,, tue는... 150일까요?

tue는 101을 갖게 됩니다.

 

enum의 값을 정하는 정의는 "이전 원소 값의 + 1" 입니다.

 

 

그럼. "왜 이넘을 사용해야 하는가.." 입니다.

 

사실 enum은 필요없을 지도 모릅니다.

#define 이 있고,

const int 가 있습니다.

 

하지만 C++ 이 enum에게 준 몇가지의 특별한 이유 때문에 enum을 사용합니다.

 

① 기억이 용이하다.

enum대신 정수형 변수를 대신 사용할 수 도 있습니다. 하지만, 이렇게 될때 각 정수의 의미가 무엇인지를 만드는 사람이 기억하고 있어야 하죠. 값이 많아질 수록 혼란스러울겁니다. 보통, 사람은 숫자보다 문자를 더 잘 기억합니다. 그리고, enum의 원소들을에게 의미를 부여한 이름을 준다면 더 기억하기가 쉽겠죠..

 

② 소스의 가독성(Readability)이 높아진다.

enum의 원소만 봄으로써, 그 상수의 의미를 보다 쉽게 파악 할 수 있고, 소스 전체의 가독성을 높이는데 도움이 됩니다. 예를 들어 whatdays = 0; 이라고 표현한다면, 이게 월요일인지,, 일요일인지, 도무지 알 길이 없습니다. 하지만 whatdays = mon; 이라고 한다면, 두말할나위없이 이해할 수 있겠죠. 두명이상의 Project나 팀단위 작업을 할때에는 알고리즘을 아무리 잘 짜도 소스가 X같으면, 프로젝트 진행이 어려워집니다. 따라서 이런 팀단위 작업에는 가독성이 아주 중요시 됩니다.

 

③ 안전하다.

앞서 예를든 days에 대입될수 있는 값은 7개중 하나로 제한이 되기때문에 사용자의 실수를 컴파일러가 미리 예방해줄 수 있습니다. 따라서 변수형을 사용하는것보다 안전하죠.

 

 

필수는 아니지만 있으면 좋다. 이게 이넘(emum)입니다.

 

 

enum을 보다 효율적으로 사용하는 방법은

 

typedef를 사용하는겁니다.

 

바로 예부터 보자면...

 

typedef enum CDays {enum {mon, tue, wed, thr, fri, sat, sun };

 

이제 CDays는 하나의 타입으로 생성된겁니다.

 

CDays WhatDay(); 와 같이 오늘이 몇요일인지 리턴하는 함수를 작성 할 수도 있구요.

 

CDays Day = WhatDay();

 

와 같이 Enum을 효과적으로 처리할 변수를 만들어 사용할 수 있습니다.

'Engineering > C Language' 카테고리의 다른 글

[C++] 구조체와 클래스  (0) 2014.02.24
[C언어] 메모리구조와 동적할당  (0) 2014.02.21
[C언어] 구조체사용하기  (0) 2014.01.16
[C언어] 포인터 사용하기-2  (0) 2014.01.15
[C언어] 포인터 사용하기-1  (0) 2013.11.30
구조체는 프로그램 개발을 위한 매우 중요한 요소로써, 앞으로 코드를 다루일이 있다면 반드시 익히 가야하는 개념입니다. 구조체는 하나이상의 변수를 묶어서 새로운 자료형을 정의하는 도구를 말합니다.

예를들어서, 학생정보시스템을 만든다고 가정할때, 학생들의 이름,키,몸무게,주소 등을 학생마다 선언하고 관리해야한다면 여간 까다롭고 귀찮은 일이 아니다. 이럴때, 구조체를 이용하면 한 학생의 정보를 표현하는 여러가지 변수를 하나로 묶어버릴수가 있다. 이렇게해서 등장한 개념이 구조체이다. 

ex)

struct student
{
char name[30];    //student구조체를 구성하는 멤버 name
int height;          //student구조체를 구성하는 멤버 height
int weight;       //student구조체를 구성하는 멤버 weight
int address;   //student구조체를 구성하는 멤버 address

}

▶ 위의 예시와 같이 구조체 변수의 선언과 접근은 아래와 같다.


struct    type_name   val_name  //구조체 변수선언의 기본 형태

         구조체 이름  /구조체 변수이름


즉, 위의 구조체 student에 구조체 변수를 선언하고자 한다면,

struct student Namja; 와 같이 선언 할수가 있다.

Namja구조체 변수 안에는 


char name[30];   
int height;        
int weight;    
int address;          

의 변수들이 존재한다. 구조체 변수를 선언함으로써 student의 멤버들을 그대로 상속받을 수가
는것이다.  

▶ 구체의 접근법은 아래와 같다.

구조체 변수의 이름.구조체 멤버의 이름

ex) Namja.height = 180;  // 구조체 변수 Namja의 멤버 height에 180을 저장

구조체를 정의함과 동시에 변수를 선언할 수도 있다.

struct student
{
int height;        
int weight;    
} boy1, girl1;

이는 student 구조체를 정의함과 동시에 student형 구조체 변수 boy1, girl1을 선언하는 문장이다.
그리고 구조체 변수의 선언과 동시에 초기화는 중괄호를 통해서 초기화할 값을 명시하면 된다.

struct student boy={"180", "75"};



▶  구조체와 배열 & 포인터

먼저, 구조체 배열이란, 구조체 변수들이 여러개 모인 배열을 의미한다. 예를들면 위의 student 구조체에서 남학생이면 10명이면 struct student boy[10]; 과 같은 형태로 구조체를 선언할수가 있다.

point형 구조체의 포인터 변수는 아래와 같이 선언되고 초기화된다.

struct student
{
int height;        
int weight;    
}

struct student boy= {178,70}; //  student형 구조체의 boy 변수를 선언과 동시에 초기화
struct student *ptr = &number;  // 구조체 point 변수 ptr이 구조체 변수 boy를 가리킨다

접근법은 
(*ptr).height=180;  // ptr이 가리키는 구조체 변수의 멤버 height에 180을 저장
(*ptr).weight=75;  // ptr이 가리키는 구조체 변수의 멤버 weight에 75를 저장


▶  typedef 선언과 구조체

typedef는 기존의 존재하는 자룡형의 이름을 사용자가 원하는 형태로 새이름을 부여하는 것을 말한다.

이것이 왜 구조체와 연관이 있는가 하면, 위의 예를 다시 가지고 설명한다면,

구조체 변수의 선언시
struct student boy; 로 선언해야 한다.

하지만 이를 typredef를 사용해서 선언후 사용한다면,


typedef struct student  Student;  // struct student 대신에 Student 이름을 부여함.


이제 struct student boy;의 명령이 간편하게 Student boy; 로 줄었다.


그래서 많은 프로그래머들이 변수의 이름의 첫글자를 대문자로 지정하여 구조체의 선언시 typedef가 적용된 형태의 축약형을 많이 사용한다. 생략가능함을 염두해 두고 코드를 유념해서 보기를 바란다.



▶ 구조체의 또다른 접근법 : 포인터 연산자 ->


이는 위의 구조체 멤버변수 접근방식 (직접방식)과는 다른 방법으로써, 간접접근 방식이라 할수가 있다.

(대부분 힙에 할당된 기억장소에 접근할 때)

= 포인터와 같은 참조변수를 이용하여 구조체 변수의 주소값에 접근하기 위해서 -> 연산자를 사용하여 접근한다.


예를 들어보자.


#include <stdio.h>

#include <stdlib.h>

#include <string.h>


typedef struct smartphone  //다음부터 smartphone만 입력하면 구조체 선언을 하도록 typedef 선언

{

char name[30];

int price;

}Apple;   // 구조체의 선언과 구조체 변수 apple의 선언.


int main(void)

{

Apple *applephone;  //구조체변수 Apple형의 참조변수 applephone선언


applephone = (Apple*) malloc(sizeof(30)); //힙에 메모리를 할당하라.

//(Apple*)는 형을 의미하고, 30 메모리 만큼의 동적할당값을 applephone 참조변수에게 할당하라. 


strcpy(Apple->name, "아이폰5");

Apple->price = 800;

printf("%s %d \n", Apple->name, Apple->price);

free(applephone);

return 0;


}



메모리 동적할당에 대한 자세한 설명은, 아래의 블로그 게시글을 참고하자.

http://rus1031.blog.me/80187120151





:: 다차원 배열 ::


다차원 배열이란? 2차원 이상의 배열을 의미한다.

즉,2,3차원을 주로 사용한다. (4차원은 이해하기 까다로워 다루지 않는다)


ex) 2차원 배열의 선언


int array1[2][5]; // 세로가2, 가로가5인 int형 2차원 배열을 의미한다,

위에서 선언된 배열의 인덱스값은 아래와 같다.


1행 1열 [0][0]

1행  2열 [0][1]

 1행 3열 [0][2]

 1행 4열 [0][3]

 1행 5열 [0][4]

2행 1열 [1][0]

2행  2열 [1][1]

 2행 3열 [1][2]

 2행 4열 [1][3]

 2행 5열 [1][4]



그리고 이들의 할당된 메모리 형태는 아래와 같다.


 0x1000

 0x1004

 0x1008

 0x100C

 0x1010

 0x1014

 0x1018 0x101C

 0x10020

 0x1024


0x1014에서 0x0014의 의미: 16^1*1 + 16^0*4 = 16+4=20


이를 통하여 알수있는 사실은, 2차원 배열도 메모리상에서는 1차원 배열의 형태로 존재한다는 사실이다.


2차원 배열의 선언과 동시에 초기화는 아래와 같다.

int arr[2][2] = { {1,2}, {3,4} };     =   int arr[2][2] = {1,2,3,4}; //동일하다. 

1,2

3,4

의 형태로 선언된 2x2 행렬의 형태로 선언과 동시에 초기화 되었다.


만약 행과 열에 정의하지않는 요소가 존재한다면, "0"으로 채워진다. 배열과 동일하다.


:: 포인터의 포인터 ::


의미 : 포인터변수를 가리키는 또다른 포인터 변수를 말하며 흔히 '이중 포인터' or '더블 포인터'라 한다.


정의 :  int ** ptr; //int 형 이중 포인터 변수 ptr 선언


앞서 설명한 포인터의 개념과 별반 다를게 없는 개념이다.

포인터 변수는 주소값만을 저장하는 변수이고, 포인터 변수또한 가리키는 포인터변수의 주소값을 저장하는 변수이다.

예를들면, 중요한 문서의 이중봉투라고 볼수가 있겠다.

int main(void)

{


int number =1;

int *ptr = &number;

int **doptr = &ptr;


}

이들 변수들이 가리키는 참조관계는 아래와 같다.

doptr -> ptr -> number =1;


*doptr은 포인터변수 ptr을 의미한다.

**doptr 또는 *(*doptr) 은 변수 number을 의미한다.


따라서, 포인터변수들의 값을 Swap하는 함수의 형태는 아래와 같아야 한다.


void Swapfunction(int **dptr1, int **dptr2)

{

int *temp = *dptr1;

*dptr1 = *dptr2;

*dptr2 = temp;


}

어떤 객체의 값을 바꿔야 되는가에 대해서, 명확하게 생각해야만 실수가 없을 것이다.

그리고 사실 삼중포인터도 존재한다. int ***tpointer; 



:: 다차원 배열과 포인터와의 관계 ::


앞장 포인터 사용하기-1에서 배열이름과 포인터와의 관계에서 가장 주요하게 언급한것이 바로

배열 이름이 해당되느 자료형 포인터이므로 


예시)

int arr[2]; //int형 포인터 arr을 선언 = 배열 arr을 선언

prinft("&p", arr+1); 


여기서  출력되는 값은 arr+sizeof(int)의 값이 출력된다. 왜냐하면, 포인터형은 포인터를 대상으로 하는 가감산연산의 결과


에서 크기를 결정하기 때문이다. 즉, 포인터형이 같다면 증가 감소의 크기값도 동일 할것이다.


하지만 다차원 배열에서는 이것만을 고려해서는 안된다.


2차원 배열이름의 포인터형은 가로의 길이에 따라서 포인터의 크기가 달라지기 때문이다.


즉, 몇개의 열을 가지고 있는가에 따라서 "다차원 배열이름"+1 = 가진 열의 수만큼 행이 하나더 생성 되기때문이다.


따라서 이 문제가 다차원 배열이름의 포인터 형 결정을 어렵게 만드는 요인이다. 


int * ExA[3];  //포인터 배열,  int형 포인터 변수로 이루어진 배열을 선언한 것.

int (*ExB)[3]; //배열 포인터, 가로길이가 3인 2차원배열을 가르키는 포인터 변수를 선언한 것.


:: 함수 포인터와 void 포인터 ::


함수 포인터 : 메모리상에 저장된 함수의 주소 값을 저장하는 포인터 변수를 의미한다.  함수도 변수처럼 메모리 공간에 저장되어서 호출시 실행되기 때문이다.


형태 :  반환형 - 포인터변수이름 - 매개변수 (즉, 반환형과 매개변수가 포함된것이 포인터 형이다)


ex) int (*simplePtr) (int);


위의 예제는 함수포인터를 선언한 형태이다. 각각의 해체해보면,

int : 반환형이 int인 함수 포인터

*simplePtr : simplePtr 은 포인터

(int) : 매개변수 선언이 int 하나인 함수 포인터


그럼 예제를 확장시켜서, 실제 함수가 존재하고 이 함수의 주소값을 저장할수있는 함수포인터를 선언해보자.


int functionA(int num1, int num2)

{

생략..

}


int (*FPtr) (int, int);


FPtr=functionA; //함수포인터에 함수의 주소값이 저장되었다.


위의 functionA라는 함수의 주소값을 저장할수있는 함수포인터의 예제이다.

그래서 실제 사용은 아래와 같이 하면 같은 결과값이 나타난다.


FPtr(1, 2); // 이는 functionA(1, 2); 와 동일한 결과를 보인다.



만약 형타입도 없고, 매개변수도 없는 함수, 즉 Void타입을 함수 포인터로 선언할 경우는 아래와 같다.

void functionA(void)

{...}


void * ptr;  //void타입의 함수 포인터 선언.



출처(cite) : http://isites.harvard.edu/icb/icb.do?keyword=k16940&state=popup&topicid=icb.topic571422&view=view.do&viewParam_name=indepth.html&viewParam_popupFromPageContentId=icb.pagecontent502214


Radio Wave Properties


[L | t++ | ★★★★] | keywords: production and detection of electromagnetic waves, dipole antenna radiation pattern, polarization of radio waves, loop antennas, E and B-field standing waves


What it shows:   The following is a sequence of experiments that can accompany a standard lecture on electromagnetic waves.  The entire sequence is quite long and you may not want to do it all in one lecture.

(1)  The voltage variation along the length of a dipole transmitting antenna can be made evident.  The intensity variation of a fluorescent light bulb, held near the antenna, shows the voltage to be maximum at the ends and minimum in the middle of the dipole.

(2)  The radio waves that radiate from the transmitting antenna are detected by a hand-held dipole receiving antenna.  Voltage and current standing waves in the receiving antenna are made evident with incandescent light bulbs (see Comments below).

(3)  The receiving antenna can be used to explore the dipole radiation pattern of the transmitting antenna.  In particular, you can show that there is no radiation along the axis of the dipole and maximum radiation perpendicular to the axis.

(4)  Polarization of the electromagnetic waves; the light bulb brightness goes from a maximum to zero as the antenna is rotated from parallelism to perpendicularity with the E-field.  A B-field loop antenna can also be used to show that the magnetic field is perpendicular to the electric field and, hence, also polarized.

(5)  Selective absorption of electromagnetic waves by a grid of copper rods, and the resulting rotation of polarization of the transmitted waves (if you like, it's Malus' Law with radio waves).

(6)  Standing waves formed by the superposition of incident and reflected waves.  By using two receiving antennas, one sensitive to the E-field and the other sensitive to the B-field, one can also demonstrate (in the case of a standing wave) that the maxima of the two fields are 180˚ out of phase with each other.

(7)  Resonance; the length of the receiving dipole antenna can be changed to "de-tune" it, and be less effective (as observed by the dimness of the light bulb).

(8)  The antenna can also be used to demonstrate the dramatic change in wavelength of the electromagnetic wave as it travels from air into water.  Submerged under water, the light bulb of the receiving antenna no longer lights.  In contrast, the light bulb of a second (much shorter) dipole antenna readily lights.  The ratio of the two antenna dipole lengths (in and out of water) is proportional to the index of refraction and the dielectric constant of water.

(9)  By coupling a long transmission line (a.k.a. Lecher line) to the RF transmitter, one can show the effects on electric standing waves along the line by either (a) shorting the end of the line, (b) having an open line, or (c) terminating the line.






How it works:  

(1)  A 300 MHz RF signal is fed to a λ/2 dipole antenna (see appendix i for details of the antenna design).  Hold one end of a 12-inch long, 8-Watt, fluorescent lamp with your hand and touch the other end of the lamp to the antenna.  Once lit, the lamp can be slid along the length of the antenna to explore the variation in voltage.  The lamp will be very bright at the two ends of the dipole, where the voltage is maximum, and very dim in the middle where the voltage is minimum — there is a voltage standing wave along the length of the transmitting antenna at resonance.

    



(2)  The radio wave receiver is astonishingly simple —  48-cm-long copper pipe serves as a λ/2 dipole receiving antenna.  Simply hold it in the middle with one hand.  While standing a couple of feet from the transmitting antenna, hold a 6-inch long, 4-Watt, fluorescent lamp in the other hand and touch either end of the copper pipe with it.  It will light up!  (The voltage standing wave set up in the copper pipe is of sufficient voltage to light the lamp.)  Slide the lamp along the length on the receiving antenna to show a voltage node in the center (the lamp goes out) and anti-nodes at the two ends — there is a voltage standing wave along the length of the receiving antenna at resonance.

    

Now try the 48-cm-long copper pipe antenna which has been split into six equal-length segments.  The segments are mechanically supported by a plastic rod and electrically connected to each other via miniature incandescent lamps.  Hold the pipe a couple of feet from the transmitting antenna and notice the intensity variation in the lamps — brightest in the middle of the dipole, tapering off to zero at the ends.  The brightness of the lamp is a qualitative indicator of the current passing through it and thus one can see, at a glance, the current variation in the receiving dipole antenna  — there is a current standing wave along the length of the receiving antenna at resonance, and it is 90˚ out of phase with the voltage standing wave.

  


Having demonstrated that the current is maximum in the middle of the dipole, you can now switch to a copper pipe antenna that is split into two equal-length segments, with one incandescent light bulb connecting the two.  Since all the power is being dissipated in a single bulb, it will be significantly brighter than the seven bulbs in the six-segment antenna.  Use this antenna as your detector for demonstrations (3) through (6).



(5)  The "polarizing filter" consists of five copper rods supported by a 1-meter square wooden frame.  The spacing between the rods is about (0.4)λ.  This "filter" is placed between the transmitting and receiving antennas.  When the rods are parallel to the transmitting antenna (i.e., E-field), the field does work in moving electrons along the length of the rods and reduces the energy in the field.  This is depicted in the figure.  Consequently, if the receiving antenna is also parallel to the rods,  very little energy reaches it and the bulb does not light.  When the rods are perpendicular to the transmitting antenna, the light bulb on the receiving antenna shows no appreciable diminuation in power received.

   

The filter can be rotated so that it is 45˚ w.r.t. the transmitting antenna.  The receiving antenna light bulb will dim, but stay lit.  If the receiving antenna is now also rotated 45˚, so that it is perpendicular to the rods, the intensity of the light increases again, notwithstanding that the receiving antenna is now tilted 45˚ w.r.t. the transmitting antenna.  This is a nice analog of rotating the plane of polarization of light with polarizing filters.

      



(6)  Allow the electromagnetic waves from the transmitting antenna to reflect off the blackboard (which has a steel backing) or some other convenient metal surface — there will be interference between the incident and reflected wave resulting in a standing wave.  By holding the receiving antenna near the reflecting surface (where the intensities of the incident and reflected wave are approximately equal), the maxima and minima of the standing wave pattern are easily shown.  The distance between maxima is λ/2 = 50 cm.

The demonstration of standing waves can be made even more interesting by employing a second receiving antenna which responds to the intensity of the magnetic field.  This antenna is a resonant loop antenna.  First, the polarization of the B-field can be demonstrated — the bulb brightness is maximum when the loop normal is parallel to B; it is zero when the normal is either along E or the propagation direction.  It's most dramatic if the electric and magnetic detectors are used simultaneously.  When this double probe is moved through the standing wave pattern in front of the reflecting surface, the brightness of the electric and magnetic detector bulbs peak at interleaving positions.  This helps to impress on the student that there are really two different fields here.  Peter Heller (Brandeis University) first demonstrated this to us at a NECUSE meeting (April 1994) and some of the insights he shared with us at the time are included in Appendix iii below.




The B-field antenna consists of a 2.75" diameter single loop formed from copper tubing.  Two small copper tabs form the capacitor.  It's resonance frequency is fine-tuned by inserting a dielectric (plastic ruler) between the capacitor plates.

   




(7)  Resonance:   the length of the receiving dipole antenna can be changed to "de-tune" it, and be less effective.  To that end, use the standard VHF "rabbit ears" antenna used on televisions.  When the telescoping sections are pulled out, the length of the antenna is no longer a resonant a λ/2 dipole, and the light bulb will be noticeably dimmer.



(8)  The wavelength change in water can be demonstrated by using the dipole antenna inside a tank of distilled water.  Submerged under water, the light bulb of the receiving antenna no longer lights.  In contrast, the light bulb of a much shorter (9 cm long) dipole antenna readily lights under water, but not in the air.  Since both antennas are adjusted to be λ/2, the ratio of the two antenna dipole lengths (in and out of water) is proportional to the index of refraction and the dielectric constant of water.  It turns out to be equal to about 5 at this frequency.



    



Setting it up:  An HP model 3200B VHF Oscillator (10-500 MHz) and EIN model 5100-L NMR RF Broadband Power Amplifier provide the RF signal.  They live together on a short relay rack which can be wheeled into place in front of the lecture bench and will not obscure the view of the blackboard. The 5-meter long BNC coax cable connects the power amplifier to the dipole transmitting antenna. The long feed allows for quite a bit of flexibility in the antenna placement. The 100-Watt power amplifier has no gain control and thus the output is set by the amplitude of the HP oscillator: the minimum amplitude setting is sufficient for this demonstration.


Comments:  The demonstrations provide a particularly striking accompaniment to the discussion of electromagnetic waves.  A light bulb is pedagogically much more convincing as a detector than a crystal diode.  After all, an electric field is "the thing that pushes electricity."  That it pushes electricity through the bulb filament strongly enough to light that filament is striking to the onlooker.  This is especially true in that no "return circuit" is present.  (If you like, the "return" is via the "displacement current.")

Safety:   The most common criteria for human exposure to electromagnetic fields are those developed by the Institute of Electrical & Electronics Engineers (IEEE) and the National Council of Radiation Protection & Measurements (NCRP).  The limit is expressed in terms of equivalent plane-wave power density and is equal to 30 W/m2.  The International Commission on Non-Ionizing Radiation Protection (ICNIRP) limit is set at 22.5 W/m2.  Exposure from the dipole transmitting antenna is well below these limits.

Appendix i:  With a wavelength of 1 meter, 300 MHz is right on the border between VHF and UHF.  The actual length of a λ/2 dipole antenna is not exactly equal to the half-wave in space, but needs to be corrected for the thickness of the conductor in relation to the wavelength.  Since the transmitting antenna is fabricated from 1/2-inch diameter aluminum rod, it is 0.48 m long.  The recipe for the correction in length is given in The Radio Amateur's Handbook, 43rd edition (1966), page 365.  An antenna with opens ends, of which the half-wave type is an example, is inherently a balanced radiator.  However, since the antenna is fed at the center through a coaxial line, this balance is upset because one side of the radiator is connected to the shield while the other is connected to the inner conductor.  On the side connected to the shield, a current can flow down over the outside of the coaxial line, and the fields thus set up cannot be canceled by the fields from the inner conductor because the fields inside the line cannot escape through the shielding afforded by the outer conductor.  Hence these "antenna" currents flowing on the outside of the line will be responsible for unbalanced radiation.  This kind of line radiation can be prevented by a device known as a balun (a contraction for "balanced to unbalanced").  Our antenna employs one type of balun called a bazooka, which uses a sleeve over the transmission line to form, with the outside of the outer line conductor, a shorted quarter-wave line section (see pages 387-388).  The impedance looking into the open end of such a section is very high, so that the end of the outer conductor of the coaxial line is effectively insulated from the part of the line below the sleeve.  The length is an electrical quarter wave, and may be physically shorter if the insulation between the sleeve and the line is other than air (which it is in our case).



Appendix ii:  The miniature incandescent lamps are type 6833, rated at 5.0V and 60mA (0.3W).  They are sometimes referred to as "grain of wheat" bulbs and have "pigtail" leads.  For the single-lamp dipole antenna we use a type 47 lamp, rated at 6.3V and 150mA (1W).  It has a bayonet base.  If you wish to increase the distance between the receiving and transmitting antennas to more than 2 meters, a more sensitive lamp is needed — use a type 1850 lamp, rated at 5.0V and 90mA (0.5W).  If using this lamp, don't come too close to the transmitting antenna as the lamp will burn out!

Appendix iii:  The B-field antenna consists of a 2.75" diameter single loop formed from 1/8" OD copper tubing.  Its inductance was calculated to be 0.14μH [F. Grover, Inductance Calculations, (D. Van Nostrand, 1946) in Cabot QC 638 G78 and F.E. Terman, Radio Engineer's Handbook, (McGraw-Hill, 1950) Cabot TK 6550.T4 are two excellent references for this].   Two small copper tabs form the capacitor.  They measure 2 cm square and are separated by 3 to 4 mm.  The capacitance is approximately 2 pF.  A thin plastic ruler between the plates serves as the dielectric — its position can be changed to adjust the capacitance.  In this way the resonance frequency can be fine-tuned to match the transmitted signal.  A type 338 (2.7V, 60mA) miniature incandescent lamb gives a visual indication of the field strength. The adjustment of the spacing between the lamp's two lead contact points provides the needed impedance matching.  With the impedance properly matched, the bulb brilliance for this "magnetic antenna" is equal to that of the λ/2 dipole antenna.

Peter Heller's thoughts on this last statement:  That this is true, despite the fact that the magnetic "loop" is only a tiny fraction of a wavelength in linear extent, beautifully demonstrates the truth of the "antenna theorem":  the absorption cross section of a resonant loop depends on its directivity pattern, and is of the order of the square of the wavelength, rather than the square of the linear dimensions, as one might have thought.  At the level of an intermediate course in electromagnetism, the fact that the resonant loop has an effective cross section many times as great (e.g. a hundred) as the square of its size, can be discussed by showing how the energy (Poynting) flux is "funneled" into the loop.  This is due to the way the incident field combines with that of the loop itself; the point here is that the loop, although it is functioning as a "receiving antenna," is also producing its own radiation field.  This field is superimposed on the original incident (plane-wave) field.  The Poynting vector field corresponding to the total field has the property that its "field lines" in a region of area of the order of the squared wavelength ultimately terminate (i.e. "flow to") the receiving loop, even though the latter is physically very much smaller than the wavelength.  He published this in the Am. J. Phys. 65(1), pp 22-25, 1997














출처 : http://timidteacher.blog.me/50179188873


*첨부파일 설명

1. 아래내용 + 영어에서 사용되는 구두점/콜론/콘마규칙/따음표/이텔릭체 등 자주 혼동스러운 모든 문자표 정리한 한글파일 입니다.

 

 

구두점과_대문자.hwp


 

 

영어공부를 하다보면, 구두점과 콜론, 세미콜론(영어 ,/:/;) 등 어떤 의미인지 의아할 때가 있습니다. 오늘 여기서 확실히 정리해 드립니다.

 

1. 마침표(.) 경우

-문장의 끝과 축양형 뒤에 찍는 것이 일반적입니다.

ex) The student go there.

 

2. 물음표(?)

-직접의문문 뒤에 붙입니다. 하지만 간접의문문 뒤에는 붙이지 않습니다.

ex) Do I have to go? (직접의문문)

ex) I do not know which one you like. (간접의문문)

 

3. 느낌표(!)

-강한 감정표현 뒤, 또는 대화나 비격식적인 서신에서 사용합니다.

ex) It is wonderful that you did so well on the game!

 

4. 세미콜론(;)

-한 문장 안에 있는 독립절 사이에 사용합니다.(; 의미는, and, but, however, because 등 모든 접속사로 이용될 수 있습니다)

ex) My father gave me the money; now I have spent all the money.

 

5. 콜론(:)

-이름, 목록, 인용 따위의 설명 중 하나를 도입하는 완결된 진술 뒤에 사용할 수 있습니다.(일반적으로 명사구 뒤에 부연설명의 기능이 많습니다)

ex) I like my classmate: Chirs Heo.

ex) I like the brands: Gucci, McM, Louisvuitton, and Prada.

 

6. 대시(―)

-삽입한 정보를 따로 제시하거나, 생각의 전환, 또는 이어 나오는 문장의 강조를 위해 사용됩니다.

ex) I have found it―Have you known it? (갑작스런 생각의 전환)

ex) I have met you―I am exciting! (강조)

 

7. 하이픈(-)

-대시와 다른 하이픈 입니다. 두개의 단어를 연결할 때, 그리고 지면이 부족한 경우, 스펠링이 다음 줄로 넘어갈 때 사용합니다.

ex) He is a well-known painter.

ex) I am a stu-

       ent. (지면이 모잘라 다음 칸으로 스펠링이 넘어가는 경우)


'English is ..' 카테고리의 다른 글

논문에서 자주 사용되는 표현들  (0) 2014.02.21
[콤마] , 의 사용법.  (0) 2014.02.04
To 부정사의 의미상의 주어  (0) 2013.05.20
some expressions..  (0) 2013.05.17
whether or not  (0) 2013.05.03

+ Recent posts