기초CS - 포인터 7

킴스코딩클럽·2022년 10월 19일
1

CS기초 시리즈

목록 보기
41/71

함수와 포인터

함수도 주소를 가진다

int Sum(int x, int y)
{
	return x + y;
}
int main()
{
	int x{ 1 }, y{ 2 };
	
	std::cout << &x << "," << &y << std::endl;
	//지역변수 주소 :0x~cc,0x~c8 주소 출력됨
	//지역변수는 대충 비슷한 곳의 주소가 출력
	std::cout << &Sum <<","<<&main<< std::endl;
	//함수의 주소 출력됨
	//많이 다른 곳의 주소가 출력됨
	std::cout <<Sum << "," << main << std::endl;
	//주소가 출력됨 &생략가능한 이유는 첫번째 원소의 주소로 나오기 때문
	//함수는 이름과 주소가 있음 (l-value 의 역할을 함)
	//그 말은 pointer가 존재한다
	//함수를 포인터해서 어디에 쓸가요??
	//스크립트를 프로그래밍할 때 사용
}

함수를 가리키는 포인터 만들기

int MyFunction(float f)
{
	return 0;
}
int(*functionP)(float f) = &MyFunction; 
// 함수 포인터 
void MyFunction(int x, float y)
{

}
int main()
{
	void (*p)(int x, float y){};
	//myfunction의 포인터 p
}

더 쉬운 방법 - 별명을 사용

using FunctionPointer = void(*)(int, float);
//함수의 포인터 타입으로 별명으로
using Function = void(int, float);
//함수의 타입을 별명으로
void MyFunction(int x, float y)
{

}
int main()
{
	void (*p1)(int x, float y){};
	//myfunction의 포인터 p
	FunctionPointer p2;
	Function* p3;
	//별명을 사용함
	p1 = MyFunction;
	p2 = MyFunction;
	p3 = MyFunction;

}

매개변수로 배열을 받아서 정렬

void Sort(int numbers[],int count)
//매개변수로 배열을 받음
{
	for (int i = 0; i < count; i++)
	{
		for (int  j = i+1; j < count; j++)
		{
			if (numbers[i] < numbers[j])
			{
				int temp{ numbers[i] };
				numbers[i] = numbers[j];
				numbers[j] = temp;
				//버블 정렬 코드
			}
		}
	}
}
int main()
{
	const int Num_array = 5;
	int scores[Num_array]{ 20,10,40,15,30 };
	Sort(scores, Num_array);
	//배열 포인터(매개변수에 포인터를 쓰는 것 : call by reference)
	//scores : call by reference
	//num_array : call by value
	//만들 배열과 부르고 난 후의 배열이 다름

	for (int i = 0; i < Num_array; i++)
	{
		std::cout << scores[i] << std::endl;
	}

}

함수 포인터를 사용한 방법

개념 : 함수가 배열처럼 작용한다


using Comparison = bool(*)(int, int);
//함수 포인터 타입

//내림차순
bool Descending(int x, int y)
{
	/*if (x < y)
	{
		return true;
	}
	else
	{
		return false;
	}
	*/
	return x < y;
}

//올림차순
bool Ascending(int x, int y)
{
	return x > y;
}


void Sort(int numbers[],int count,Comparison f)
//매개변수로 배열을 받음
{
	for (int i = 0; i < count; i++)
	{
		for (int  j = i+1; j < count; j++)
		{
			if (f(numbers[i],numbers[j]))
				//함수 부르기
				//이미 함수가 포인터임을 알고있음
				//역참조를 하지않아도 작동하도록 만들어짐
			{
				int temp{ numbers[i] };
				numbers[i] = numbers[j];
				numbers[j] = temp;	
			}
		}
	}
}
int main()
{
	const int Num_array = 5;
	int scores[Num_array]{ 20,10,40,15,30 };
	//내림
	Sort(scores, Num_array,Descending);
	//오름
	Sort(scores, Num_array, Ascending);
	

	for (int i = 0; i < Num_array; i++)
	{
		std::cout << scores[i] << std::endl;
	}

}

문자열과 포인터

배열이 포인터니까 문자열도 포인터로 가능함


//char str1[6]{ 'd','c','c','a','d','\0' };
	char str1[6]{ "dccad" };
	//같은 내용
	char* p{ &str1[0] };
	
	std::cout << str1 << std::endl;
	//dccad
	std::cout << p << std::endl;
	//dccad
	//char pointer는 다른 말로 문자열이다
	//말 그대로 문자열이므로 그 포인터가 가리키는 문자열이 출력됨
	
	const char* p2 = "dccad";
	//우측값참조로 문자열 가리키는 포인터 사용가능

	const char* p = p2;
	std::cout << p + 3 << std::endl;
 //0번째 칸에서 +3부터 출력 gy

한글이면?

const char* p2 = "안녕하세요";
	//우측값참조로 문자열 가리키는 포인터 사용가능

	const char* p = p2;
	std::cout << p + 3 << std::endl;
	//한글 2byte >>한글이 깨짐

문자열의 숫자를 새는 방법

  • null문자로 끝나기 때문에 숫자가 필요없어 쉬움

  • c스타일의 기능을 이용해보기

    //문자열 - null terminated, 배열 = 포인터 
    int GetLength(char* pc)//pointercharacter
    {
    	int count{};
    	while (*pc != '\0')
    	{
    		pc++;
    		count++;
    	}
    
    	return count;
    }
    int main()
    {
    	char input[1000];
    	std::cin >> input;
    	std::cout << GetLength(input) << std::endl;
    }

#include <iostream>
#include<cstring>

//문자열 - null terminated, 배열 = 포인터 

int GetLength(char* pc)//pointercharacter
{
	int count{};
	while (*pc != '\0')
	{
		pc++;
		count++;
	}

	return count;
}

int main()
{
	char input[1000];
	std::cin >> input;
	std::cout << GetLength(input) << std::endl;
	std::cout << strlen(input) << std::endl;
}
profile
공부 기록용

0개의 댓글