• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

14.26강 연습문제 질문이 있습니다.

24.01.27 20:20 작성 24.01.27 20:25 수정 조회수 99

2

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>

void update_string(char*, int(*)(int));
void ToUpper(char*);
void ToLower(char*);
void Transpose(char*); // TO DO : add a new menu

int main(void)
{
	char options[] = { 'u', 'l' };
	int n = sizeof(options) / sizeof(char);

	// 함수 포인터의 배열
	typedef void (*FUNC_TYPE)(char*);
	FUNC_TYPE operations[] = { ToUpper, ToLower };

	printf("Enter a string\n>> ");
	
	char input[100];

	while (scanf("%[^\n]%*c", input) != 1)
		printf("Please try again.\n>> ");

	printf("Choose an options:\n");
	printf("u) to upper\n");
	printf("l) to lower\n");

	char option_choice;
	while(scanf("%[^\n]%*c", &option_choice) != 1)
		printf("Please try again.\n>> ");

	// 선택한 옵션에 따라 대문자/소문자로 변경
	// options 배열을 순회하며 options에서 선택한 옵션의 index 추출
	int option_choice_index = 0;
	for (int i = 0; i < n; ++i) {
		if (options[i] == option_choice) {
			option_choice_index = i;
			break;
		}
	}

	// 문자열 변경 함수 실행
	update_string(input, operations[option_choice_index]);

	// 문자열 출력
	puts(input);

	return 0;
}

// 문자열 전체를 대문자/소문자로 변경하는 함수
void update_string(char* str, int(*ptr_func)(int))
{
	char* arg1 = str;
	int(*arg2)(int) = ptr_func;

	(*ptr_func)(str);
};

// 문자열 전체를 대문자로 변경하는 함수
void ToUpper(char* str)
{
	char* arg3 = str;

	while (*str != '\0') {
		*str = toupper(*str);
		str++;
	}
};

// 문자열 전체를 소문자로 변경하는 함수
void ToLower(char* str) 
{
	while (*str != '\0') {
		*str = tolower(*str);
		str++;
	}
};

 

update_string 함수에서(*ptr_func)(str);를 실행할 때까지 str의 주소가 잘 잡힙니다.

그런데 (*ptr_func)(str);를 실행해서 ToUpper 함수 안으로 진입하면 str의 주소가 잡히지 않는데 왜 이런지 잘 모르겠습니다..

 

답변 1

답변을 작성해보세요.

2

Soobak님의 프로필

Soobak

2024.01.28

안녕하세요, 질문&답변 도우미 Soobak 입니다.

 

작성하신 코드 중 update_string() 함수가 받는 함수 포인터의 타입은 int(*)(int) 으로 선언되어 있습니다.
반면, ToUpper() , ToLower() 과 같은 함수들은 void(*)(char*) 타입으로 선언되어 있으므로, 타입 불일치와 관련하여 문제가 생길 수 있습니다.

 

또한, update_string() 함수 내부에서 (*ptr_func)(str); 호출이 이루어질 때,
ptr_func 이 가리키는 함수는 int 타입의 인수를 받도록 선언되어 있습니다.
하지만, strchar* 타입입니다.
따라서, 이 타입 불일치 때문에 예상치 못한 동작이 발생하는 것으로 보입니다.

 

void update_string() 의 선언을 다음과 같이 변경해보세요.

void update_string(char* str, void (*ptr_func)(char*))
{
    char* arg1 = str;
    void (*arg2)(char*) = ptr_func;

    ptr_func(str);
};

 

참고 이미지 첨부

image

image

아.. 함수 호출할 때 인수의 자료형을 생각 못하고 있었네요..

캡쳐까지 포함해서.. 정말 항상 상세한 답변 감사드립니다..!!!!