출처 : www.cfaq.com

Q: I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn't

((int *)p)++;

work?

int 형 포인터인데 왜 저렇게는 증가가 안되는건가?   

A: In C, a cast operator does not mean ``pretend these bits have a different type, and treat them accordingly''; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a deliberate but nonstandard extension if a particular compiler accepts expressions such as the above.) Say what you mean: use

        p = (char *)((int *)p + 1);

or (since p is a char *) simply

        p += sizeof(int);

or (to be really explicit)

        int *ip = (int *)p;
        p = (char *)(ip + 1);

When possible, however, you should choose appropriate pointer types in the first place, rather than trying to treat one type as another.

See also question 16.7.

References: K&R2 Sec. A7.5 p. 205

ISO Sec. 6.3.4

Rationale Sec. 3.3.2.4

H&S Sec. 7.1 pp. 179-80

반응형

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

mmap / munmap 함수 예제  (10) 2012.07.17
shmget/ shmat 함수 예제  (6) 2012.07.13
nmemb 의미  (8) 2012.07.12
msgsnd/ msgrcv 함수 예제  (12) 2012.07.12
C FAQ (포인터 증가 2)  (6) 2012.07.12

+ Recent posts