출처 http://c-faq.com

Q: I'm trying to use pointers to manipulate an array of ints. What's wrong with this code?

        int array[5], i, *ip;
        for(i = 0; i < 5; i++) array[i] = i;
        ip = array;
        printf("%d\n", *(ip + 3 * sizeof(int)));

I expected the last line to print 3, but it printed garbage.

   scaleing을 위해서 뒤에다가 sizeof(int)를 곱해줬는데 이걸로 인해서 존재하지 않는 영역을
건드리게 되면 위와 같이 에러가 난다. 게다가 sizeof(int)는 내가 사용하는 장비에 따라 싸이즈도
다르다. 포인터에서는 자동적으로 스케일되기 때문에 사이즈에 대한 고려는 해주지 않아도
된다는 내용.

A: You're doing a bit more work than you have to, or should. Pointer arithmetic in C is always automatically scaled by the size of the objects pointed to. What you want to say is simply

        printf("%d\n", *(ip + 3));        /* or ip[3] -- see Q 6.3 */

which will print the third element of the array. In code like this, you don't need to worry about scaling by the size of the pointed-to elements--by attempting to do so explicitly, you inadvertently tried to access a nonexistent element past the end of the array (probably array[6] or array[12], depending on sizeof(int) on your machine).

See, however, question 7.19b.

References: K&R1 Sec. 5.3 p. 94

K&R2 Sec. 5.4 p. 103

ISO Sec. 6.3.6

H&S Sec. 7.6.2 p. 204

반응형

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

nmemb 의미  (8) 2012.07.12
msgsnd/ msgrcv 함수 예제  (12) 2012.07.12
C FAQ (포인터 증가에 대해서)  (6) 2012.07.12
C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가?  (6) 2012.07.12
C FAQ (malloc 오류)  (6) 2012.07.12

+ Recent posts