C언어 문자열 포인터 Swap 예시 코드

포인터 변수 자체의 값을 바꾸려면 포인터의 주소를 함수에 전달해야 한다. 문자열 리터럴을 가리키는 포인터 세 개를 순환 이동하는 예제다.




#include <stdio.h>

void rotate(char **first, char **second, char **third) {
    char *temp = *first;
    *first = *second;
    *second = *third;
    *third = temp;
}

int main(void) {
    char *name = "mlog";
    char *age = "26";
    char *tall = "secret";

    rotate(&name, &age, &tall);
    printf("%s\n%s\n%s\n", name, age, tall);
}




함수 인자가 char **인 이유는 호출자 쪽의 char * 변수 자체를 수정해야 하기 때문이다.

Comments

댓글을 불러오고 있습니다.