티스토리 툴바

   개발자 로니강(Ronie.Kang)  
Front Page
Tag | Location | Media | Guestbook | Admin   
 
'Programming/C'에 해당하는 글(6)
2009/12/02   큰 실수 -_-;;;; (5)
2009/07/01   Hello World가 실행 파일이 될때까지...
2008/08/18   Little-Endian to Big-Endian
2008/07/17   다시 들쳐 보는 문법 및 레퍼함수 - fseek (2)
2008/06/30   복잡한 포인터(Pointer) 읽기
2008/05/23   포인터 읽기 (15)


큰 실수 -_-;;;;
초보중에서도 초보가 할 수 있는 copy and paste를 통해서
아래와 같은 코드를 만들어 냈다. ㅜㅜ

하늘을 보기가 부끄럽다.!!!!
(친구 : "인간은 실수하는 동물"라는 말에 조금은 위로하고 Code Review에 힘써야겠다.)




void *xx_mem_get(size)
{
    void *mem = (void *)malloc(size);
    if(mem == NULL) {
        error ( ~ ~~~ );
    }

    return malloc(sizeof(size));
}



크리에이티브 커먼즈 라이선스
Creative Commons License
Tag : It, malloc, Memory Leak, 메모리 누수, 바보짓, 실수
Commented by 윤경록 at 2009/12/10 19:48  r x
ㅠ.ㅠ 자책하지마..
내가 한 실수(덧셈 틀림 1+2=5)로 앞으로의 모든 배포가 그 실수를 포함하여 배포되도록 결정되어 버렸어. 하위 호환성 때문에.. OTL
Replied by 윤경록 at 2009/12/10 19:48 x
그래도 3밖에 차이 안나... ㅡㅠㅡ
Replied by 윤경록 at 2009/12/10 19:49 x
아... 2다..
Commented by 신동호 at 2009/12/16 05:50  r x
저게 정상적으로 실행되게 하는 방법은 없을까...?
Replied by Ronie.Kang at 2009/12/28 15:59 x
걍 수정 해버렸지요^^

name    password    homepage
 hidden


Hello World가 실행 파일이 될때까지...
우선 간단하게 컴파일이 되는 아래 Hello World를 작성한다.

helloworld.c

펼치기



컴파일러들을 이용하여 실행할 수 있는
실행 파일로 만드는 과정을 간단하게 적어 보면

Preprocessor --> Compiler -->Assembler  --> Linker & Relocation--> executableFile

1. 컴파일러는 helloworld.c 파일을 읽어들인다.
    (확장자에 따라 c / c++로 인식)

2. helloworld.c에 Code를 오브젝트 파일로 만든다.

3. 중간 목적 파일(기계어)로 변경한다 .

4. 중간 목적 파일을 링커 프로그램으로 연결한다.

5. exe  실행파일
크리에이티브 커먼즈 라이선스
Creative Commons License
Tag : C, Hello World!!

name    password    homepage
 hidden


Little-Endian to Big-Endian

MP4 Decoder에 Video Fream을 넘겨 줄때 앞에 4byte에 Length를 넣으라는
양키의 말에 급조해서 만들긴 했습니다.
더 좋은 코드가 있다면 언제든지 리플과 수정 부탁 드립니다.

UINT my_htonl( UINT nSource )
{
 if( 0 == nSource )
  return 0;

 UINT nResult = 0;
 nResult =  (nSource <<24);
 nResult  =  nResult  | ( 0x00ff0000 & (( nSource << 16) >>8) );
 nResult  =  nResult  | ( 0x0000ff00 & (( nSource << 8) >>16) );
 nResult  =  nResult | ( 0x000000ff & ( nSource >>24 ) );

 return nResult
}




자세히 설명이 나와 있습니다.
아래 링크를 참고 하세요.

http://ssulsamo.egloos.com/3150581
크리에이티브 커먼즈 라이선스
Creative Commons License
Tag : big-endian, little-endian, 리틀엔디, 빅엔디안

name    password    homepage
 hidden


다시 들쳐 보는 문법 및 레퍼함수 - fseek

제목을 어떻게 붙일까하다가 "다시 들쳐 보는 문법 및 레퍼함수"이라 하였다.
특별히 fseek를 사용하는데 어려운 일이 있는 것도 아니다.

다만 가물 가물 해져가는 기억을 위해 실험하고 기록하여
이짓( IT )을 오래도록 해먹기 위한 발악쯤으로 생각 하면 될 듯...


fseek를 MSDN을 참조하면...

* 특정 위치로 파일의 포인터를 움직인다.
* 64bit를 위한 offset이 존재 한다는 것을 알 수 있다.

msdn에서 함수에 대한 설명을 볼때 가장 중요하게 볼 것은 역시,
인자 값과, 리턴 값일 것이다. 아래 내용을 잘 살펴보면

"If successful, fseek and _fseeki64 returns 0. Otherwise, it returns a nonzero value. "
성공과 실패에 대한 return 값을 정의하고 있다.

MSDN을 살펴보면 친절하게도 예제 코드도 제공 해준다.
굿이다.

Moves the file pointer to a specified location.

int fseek( 
   FILE *stream,
   long offset,
   int origin 
);
int _fseeki64( 
   FILE *stream,
   __int64 offset,
   int origin 
);

Parameters

stream

Pointer to FILE structure.

offset

Number of bytes from origin.

origin

Initial position.

If successful, fseek and _fseeki64 returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined. If stream is a null pointer, or if origin is not one of allowed values described below, fseek and _fseeki64 invoke the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, these functions set errno to EINVAL and return -1.

The fseek and _fseeki64 functions moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin. The next operation on the stream takes place at the new location. On a stream open for update, the next operation can be either a read or a write. The argument origin must be one of the following constants, defined in STDIO.H:

SEEK_CUR

Current position of file pointer.

SEEK_END

End of file.

SEEK_SET

Beginning of file.

You can use fseek and _fseeki64 to reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file. fseek and _fseeki64 clears the end-of-file indicator and negates the effect of any prior ungetc calls against stream.

When a file is opened for appending data, the current file position is determined by the last I/O operation, not by where the next write would occur. If no I/O operation has yet occurred on a file opened for appending, the file position is the start of the file.

For streams opened in text mode, fseek and _fseeki64 have limited use, because carriage return–linefeed translations can cause fseek and _fseeki64 to produce unexpected results. The only fseek and _fseeki64 operations guaranteed to work on streams opened in text mode are:

  • Seeking with an offset of 0 relative to any of the origin values.
  • Seeking from the beginning of the file with an offset value returned from a call to ftell when using fseek or _ftelli64 when using _fseeki64.

Also in text mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing, fopen and all related routines check for a CTRL+Z at the end of the file and remove it if possible. This is done because using the combination of fseek and ftell or _fseeki64 and _ftelli64, to move within a file that ends with a CTRL+Z may cause fseek or _fseeki64 to behave improperly near the end of the file.

When the CRT opens a file that begins with a Byte Order Mark (BOM), the file pointer is positioned after the BOM (that is, at the start of the file's actual content). If you have to fseek to the beginning of the file, use ftell to get the initial position and fseek to it rather than to position 0.

This function locks out other threads during execution and is therefore thread-safe. For a non-locking version, see _fseek_nolock, _fseeki64_nolock.

Function Required header Compatibility

fseek

<stdio.h>

ANSI, Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003

_fseeki64

<stdio.h>

Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003

For additional compatibility information, see Compatibility in the Introduction.

// crt_fseek.c
// This program opens the file FSEEK.OUT and
// moves the pointer to the file's beginning.
 
#include <stdio.h>

int main( void )
{
   FILE *stream;
   char line[81];
   int  result;

   if ( fopen_s( &stream, "fseek.out", "w+" ) != 0 )
   {
      printf( "The file fseek.out was not opened\n" );
      return -1;
   }
   fprintf( stream, "The fseek begins here: "
                    "This is the file 'fseek.out'.\n" );
   result = fseek( stream, 23L, SEEK_SET);
   if( result )
      perror( "Fseek failed" );
   else
   {
      printf( "File pointer is set to middle of first line.\n" );
      fgets( line, 80, stream );
      printf( "%s", line );
    }
   fclose( stream );
}

Output

File pointer is set to middle of first line. This is the file 'fseek.out'.
크리에이티브 커먼즈 라이선스
Creative Commons License
Commented by 요츠바랑 at 2008/07/18 22:47  r x
쩝....수학은 좋아하지만 컴퓨터 관련 용어만 나오면 작아지네요 ㅠ
Replied by Ronie.Kang at 2008/07/21 12:09 x
아하 저는 수학만 나오면 작아지네여..~~^^

name    password    homepage
 hidden


복잡한 포인터(Pointer) 읽기
제가 종종 들리는 신영진님의 "지니야 넷"에서 훔쳐 온 글입니다.
원문 그대로 옮겼습니다. 트랙백을 통해서 글을 연결하고 싶지만,,,,,;;,,,,

원문이 없어지는(?) 일이 종종 있어서 아쉬운 마음에 담아왔습니다.
널은 아량으로 용서를 빕니다. ~

복잡한 포인터를 읽는 법에 대해서 잘 설명을 해주셨습니다.
좌에서 우로~ 3가지의 표현을 영어로 해석하게 되면
아무리 복잡한 포인터라도 의미를 쉽게 알 수 있습니다.

팀내 친한 선배님(이의진 책임님)은 안에서 "원을 그리며 읽어라"라고 하셨습니다.
거의 일맥 상통한다 볼 수 있습니다.

저도 또한 포인터를 많이  사용합니다.
Callback Function을 주로 사용하거나, Struct에 Fucntion Pointer member를 이용하여
구조체 자체를 넘기기도 하고, 2차 배열 동적할당을 위해서 사용하기도 합니다.

포인터는 어려운 것이 아닙니다. 다만 프로그래밍을 싫어하는(?) 선배들에 의해서
포인터가 어렵데 어렵데라는 말에 벌써 벌벌 떨진 않았나 돌아 봅니다.

포인트를 이해 하기위해서는 약간의 자기만의 이해 방법이 있어야 하고 ~
도서관에서 얇은 책을 보고도 포인터를 알 수도 있습니다.
알려고 노력 했을 경우 입니다. ^^

혹시 포인터 말고도 더 많은 지식을 얻고자 한다면 아래 신영진 님의 싸이트를
방문 해보시면 ..^^ 살이 되고 피가 되는 좋은 내용들을 얻을 수 있을 것입니다.

그럼 고운하루 되세요~!



신입 개발자를 위한
복잡한 포인터 선언을 해석하는 방법
신영진 pop@jiniya.net http://www.jiniya.net

C언어 게시판에 자주 올라오는 질문 중에 하나가 복잡한 포인터 선언문을 해석하는 것들이다. 대부분의 학생들은 이것을 막연히 외우려고 한다. int *a[3]은 int 포인터를 저장하는 배열이고, int (*a)[3]은 int 배열에 대한 포인터라고 외우는 것이다. 하지만 이렇게 외운 지식은 그 형태가 조금만 달라져도 무용지물이 된다. 그렇다면 어떻게 해야 이러한 선언문을 손쉽게 해석할 수 있을까? 간단한 규칙만 이해하면 된다.

복잡한 선언을 정확하게 이해하기 위한 첫 단계는 선언문 내부에 나타나는 각 요소의 정확한 의미를 이해하는 것이다. <표 1>에는 선언문 내부에 나타나는 각 구성요소의 의미와 사용 예가 나와있다. 선언문을 해석할 때 영어를 이용하면 굉장히 편리하게 해석할 수 있다. 따라서 각 기호에 맞는 영어 표현도 같이 알아두는 것이 좋다.

표 1 표현식에 나타나는 기호들의 의미

기호

표현

의미

*

pointer to

특정 대상체를 가리키는 포인터

int *a;

a int 형을 가리키는 포인터다.

[]

array of

특정 대상체를 저장하는 배열

int a[3];

a int 3개 저장할 수 있는 배열이다.

()

function

인자를 받고 값을 리턴하는 함수

int a();

a는 인자가 없고 int를 반환하는 함수다.


다음으로 이해해야 하는 것은 선언문을 해석하는 순서다. 선언문은 선언 대상이 되는 변수 명에서 시작해서 오른쪽으로 가면서 해석한다. 선언문의 끝이나 오른쪽 괄호를 만나면 방향을 바꾸어 왼쪽으로 가면서 해석한다. 왼쪽으로 가면서 해석을 하다 왼쪽 괄호를 만나면 다시 오른쪽으로 가면서 해석한다. 이렇게 해서 선언문의 가장 왼쪽 끝에 도달하면 해석이 마무리 된다.

표 2 복잡한 표현식들의 해석 순서와 해석 결과

표현식

해석 순서

해석 결과

int **a;

 

a => a; => *a; => **a; => int **a;

a is a pointer to pointer to int

a int를 가리키는 포인터의 포인터다.

int *a[3];

 

a => a[3] => a[3]; => *a[3]; => int *a[3];

a is an array of 3 pointer to int

a int를 가리키는 포인터를 세 개 저장하는 배열이다.

int (*a)[3];

 

a => a) => (*a) => (*a)[3] => int (*a)[3]

a is a pointer to array of 3 int

a int 세 개를 저장하고 있는 배열을 가리키는 포인터다.

int *(*(*fp1)(int))[10];

fp1 => fp1) => (*fp1) => (*fp1)(int) => (*fp1)(int)) => (*(*fp1)(int)) => (*(*fp1)(int))[10] => *(*(*fp1)(int))[10]; = > int *(*(*fp1)(int))[10];

fp1 is a pointer to function that takes an int as an argument and returns a pointer to an array of 10 pointers to ints.

fp1 int를 인자로 받고 int에 대한 포인터를 열 개 저장하는 배열을 가리키는 포인터를 리턴하는 함수에 대한 포인터다.

char *(*(**foo[][8])())[];

foo[] => foo[][8] => *foo[][8] => (**foo[][8]) => (**foo[][8])() => *(**foo[][8])() => (*(**foo[][8])())[] => char *(*(**foo[][8])())[]

foo is an array of array of 8 pointers to pointer to function that returns a pointer to array of pointer to char.

foo char를 가리키는 포인터를 저장하는 배열을 가리키는 포인터를 리턴하는 함수에 대한 포인터를 가리키는 포인터를 8개 저장할 수 있는 배열에 대한 배열이다.


크리에이티브 커먼즈 라이선스
Creative Commons License

name    password    homepage
 hidden


포인터 읽기

일전에 비슷한 글을 읽은 적이 있습니다.
다중 포인터를 쉽게 읽는 방법이라는 글이었는데..
도통 기억이 나지 않는군여. 여튼 각설하고
제가 종종 들려 이것 저것 훔쳐 오는
http://www.troot.co.kr/trbbs/zboard.php?id=newgal&no=1427
에서 담아 옵니다.

트랙백을 찾다 못 찾았습니다.

최초 작성자는
http://blog.cnrocks.net/   라는 분입니다.


고운하루 되세요.!
크리에이티브 커먼즈 라이선스
Creative Commons License
Commented by 씨에 at 2008/06/06 11:37  r x
해당 글은 redbaron님 서버에서 증발되었습니다. 의외로 그 글의 리퍼러가 많은 것 같네요.
Replied by Ronie.K at 2008/06/12 12:30 x
글을 긁어 온다는게 ~
광고 까지 긁어 왔네요...^^

고운하루 되세요!!
Commented by 씨에 at 2008/06/28 12:50  r x
사실 저는 저 글의 최초 작성자는 아니고요. 어떻게 읽어야 하는지에 대한 글을 올렸습니다. 글이 날라가 버려서 찾을 수가 없네요 :)
Replied by Ronie.Kang at 2008/06/30 17:40 x
^^ 넹 ~ 내용을 수정 해두겠습니다.
고운하루 되세요..~!!
Commented by zeroxy at 2008/07/08 20:05  r x
퍼갈께요..긁어가도돼나요??ㅡ.ㅡ;;
Replied by ronie.kang at 2008/07/09 10:00 x
네 ^^ 그러셔도 되요.
포인터와 관련된 더 좋은 글이 있습니다.

복잡해 보이는 포인터 읽기라는 글이 있는데
그것도 참고 하세요
그럼 고운 하루 되세요~
Commented by 스티브 at 2008/11/28 14:59  r x
제 경우는 영어로 바꾸어서 읽는게 가장 쉬운 것 같습니다.
컴파일 순서대로 바꾸는거죠. 포인터는 pointer to, 배열은 array of.
Replied by Ronie.Kang at 2008/11/28 21:20 x
넹 영어로 *를 변환해서 읽는것이 가장 쉽습니다.
^^ 제가 처음 본 자료도 영어로 되어 있는것이에요
Commented by Darla35Alexander at 2011/10/21 00:20  r x
I think that to receive the <a href="http://goodfinance-blog.com/topics/credit-loans">credit loans</a> from creditors you must have a firm motivation. However, one time I have received a short term loan, because I wanted to buy a car.
Commented by write my paper at 2011/10/25 11:45  r x
Finally you do not have to waste your valuable time for writing, you must buy papers online and take a rest.
Commented by Buy a Paper at 2011/10/26 08:09  r x
We have to be careful! There're lots of scam companies that offer research essays of poor quality. It is dangerous to buy Research papers online at such companies.
Commented by buy a research paper at 2011/10/26 12:10  r x
Do not want to be disappointed anylonger? Have got heavy research papers to write? Don't know even the correct way to start? Worry no more and just buy term paper!
Commented by write my essays at 2011/10/27 08:24  r x
You can higher rates if buy essay term paper. Nonetheless, you should have no doubts and do you decision immediately!
Commented by buy an essay at 2011/10/31 09:53  r x
In the essay writing service it is very easy to get some facts and essay writing about this topic . To do easier your scholar career buy essay and feel your free time!
Commented by submit articles at 2011/10/31 13:29  r x
Not lots of guys can to do their websites' improvement themselves. Therefore, that is important to turn to expert article submission site which will offer any SEO work.

name    password    homepage
 hidden


BLOG main image
개발자 로니의 스토리.... 삽질, 날샘, 야근, 개발, 자취생, 일상, 프로그래밍 개발, 등등등....
 Notice
 Category
분류 전체보기 (191)
매일매일갱생 (76)
아이폰 (0)
Books (3)
Programming (86)
BroadCast (12)
Personal Projects (6)
유용한 프로그램 (0)
비공개 (0)
 TAGS
빵꾸똥꾸 SIP 아이폰 C++ ubuntu itunes 동기화 iTunes Porter-Duff 토렌토 바보짓 VirtualBox iPhone M480 조중동 torrent C 인터넷전화 메모리 누수 벨소리 변경 myLG070 malloc 아이튠즈 MB 용자 가카 강남역 It arduino uno 스마트폰 sip 해킹 Linux 미라지 Memory Leak 벨소리 iphone 개발환경 directfb warning usb 인식 국내 토렌토 실수
 Calendar
«   2012/05   »
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    
 Recent Entries
Finding Memory Leaks Using t.. (3)
Program Arduino with AVR-GCC
새로운 장난감....
ATMEGA328P-PU
Arduino uno 간단한 보드 설명.
퇴근길 강남역에서 만난 도인?.. (1)
xper 5월 정기모임이 일정 (1)
국내 토렌토 주소 모음
미라지(SKT) M480 벨소리 변경..
myLG070 sip 추출하기 (3)
warning: braces around scala..
 Recent Comments
This posting on the..
MBA finance dissertation - 13:50
very nice blog and..
Management Thesis topic - 02:01
Here are some recom..
america essay paper - 04/20
Students’ life tim..
technology essays - 04/20
The texts about thi..
buy essay - 04/17
Some people like to..
buy essay - 04/17
The the web is floo..
buy thesis - 04/14
That is not really..
custom thesis - 04/14
The best thesis can..
custom dissertation - 04/12
The thesis service..
custom dissertation - 04/12
There’re lots of w..
writer job - 04/11
 Recent Trackbacks
COFDM 방식에서의 Bi..
Steve Yoon's log
다중포인터 읽기
.
 Archive
2011/09
2010/06
2010/05
2010/04
2010/02
2010/01
2009/12
2009/11
2009/10
2009/09
 Link Site
zextor
괴짜 프로그래머의 일상사~@@
Gag & Peace, and more..
Kazakhstan Almaty.......
Min-A
Sadgarret
Steve Yoon's log
가슴 뛰는 삶을 살아라
오스틴 파워
GUI sin
melanie parker_Lady
제레미의 TV 2.0 이야기..
 Visitor Statistics
Total : 89,279
Today : 1
Yesterday : 63
rss