C/C#/C++/C

C언어 포인터 익히는 중

Alyce 2015. 7. 1. 17:45
char * name = "John";

does three things:

  1. It allocates a local (stack) variable called name, which is a pointer to a single character.
  2. It causes the string "John" to appear somewhere in the program memory (after it is compiled and executed, of course).
  3. It initializes the name argument to point to where the J character resides at (which is followed by the rest of the string in the memory).

Dereferencing a pointer is done using the asterisk operator *.

Notice that we used the & operator to point at the variable a, which we have just created.


(*n)++;
Notice that when calling the addone function, we must pass a reference to the variable n, and not the variable itself - this is done so that the function knows the address of the variable, and won't just receive a copy of the variable itself.

void move(point * p) {
    (*p).x++;
    (*p).y++;
}
void move(point * p) {
    p->x++;
    p->y++;
}

같음


return 은 함수가 아니라, C언어의 키워드(keyword) 즉 "예약어"입니다. C언어에서는 뒤에 소괄호"()"가 없으면 함수가 아닙니다. (▶▶ "[C언어] C언어와 C++의 예약어 리스트; Keywords" 참조)

(참고로, 펄(Perl)의 함수에서는 소괄호를 생략할 수 있음)


return 은, 현재 있는 함수에서 빠져나가며, 그 함수를 호출했던 곳으로 되돌아 가라는 뜻입니다. 되돌아 가면서 그 함수를 호출했던 곳 즉 calling routine 에 어떤 값을 반환하는 것입니다.

return 0; 는 0 이라는 값을 반환하라는 의미이고
return 1; 은 1 이라는 값을 반환하라는 뜻입니다.

return 은 함수의 어떤 곳에서도 위치할 수 있는데, return 이 실행되는 즉시 그 함수는 무조건 실행이 종료됩니다.

즉, 현재의 함수에서 빠져 나가라는 의미입니다.



* 그 함수가 무엇을 계산하는 함수라면, 그 계산 결과의 값을 return 으로 반환합니다.
* 계산이 아닌, 어떤 일을 하는 함수라면, 그 일이 성공했을 때에는 0 을, 실패했을 때에는 1 을 반환하며 끝내는 것이 보통입니다. 그러면 그 함수를 호출한 곳에서, 그 함수가 제대로 실행되었는지 판단할 수가 있습니다.