출처 http://c-faq.com
Q: I'm trying to declare a pointer and allocate some space for it, but it's not working. What's wrong with this code?
char *p;
*p = malloc(10);
=> 언뜻 보기에는 될것 같이 생겼다..
A: The pointer you declared is p, not *p. When you're manipulating the pointer itself (for example when you're setting it to make it point somewhere), you just use the name of the pointer:
p = malloc(10);
It's when you're manipulating the pointed-to memory that you use * as an indirection operator:
*p = 'H';
(It's easy to make the mistake shown in the question, though, because if you had used the malloc call as an initializer in the declaration of a local variable, it would have looked like this:
char *p = malloc(10);
When you break an initialized pointer declaration up into a declaration and a later assignment, you have to remember to remove the *.)
In summary, in an expression, p is the pointer and *p is what it points to (a char, in this example).
See also questions 1.21, 7.1, 7.3c, and 8.3.
References: CT&P Sec. 3.1 p. 28
C FAQ (포인터 증가에 대해서) (7) | 2012.07.12 |
---|---|
C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가? (7) | 2012.07.12 |
C FAQ (포인터 선언 에러) (7) | 2012.07.12 |
mkfifo 함수 예제 (471) | 2012.07.06 |
popen 함수 pclose 함수 예제 (175) | 2012.07.06 |