오타루 C++ 여러 장 8 (3) 포인터와 문자열, (4) 함수와 포인터

목차

3. 함수와 문자열

4, 함수 및 포인터

4.1 함수 매개변수로서의 포인터

4.2 함수 반환 포인터

4.3 함수 포인터와 함수 포인터 배열

4.4 구조 포인터 


​​​​​​​​​​​​​​Otaru C++ 여러 장 8 (1) 포인터 변수 icon-default.png?t=N176https://blog.csdn.net/weixin_44775255/article/details/129031168

오타루 C++ 다중장 8(2) 포인터와 배열 icon-default.png?t=N176https://blog.csdn.net/weixin_44775255/article/details/129396791

3. 함수와 문자열

문자열 얘기가 나와서 말인데, 문자열 라이브러리를 가져와야 합니다 : #include<cstring>

문자열의 일반적인 방법을 알아보세요. strcpy, strcmp, strstr, strlen.

//字符串 
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[100],b[100]; 
int main(){
	strcpy(a,"hello");
//	cout<<a<<endl;
	printf("%s,len=%d\n",a,strlen(a)); //字符串长度 
	
	scanf("%s",b);
	int cmp = strcmp(a,b); //字符串比较大小 
	if(cmp==0){
		printf("%s=%s\n",a,b);
	}
	else if(cmp<0){
		printf("%s<%s\n",a,b);
	}
	else{
		printf("%s>%s\n",a,b);
	}
	if(strstr(a,b)!= NULL){ 	//查找子串 
		printf("%s in %s\n",b,a); 
	}
	return 0;
} 

난이도: strcpy 와 strlen의 기원을 구체적으로 살펴보겠습니다 .

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char *strcpy(char *dest,const char *scr){
	char *p=dest;
	while(*scr != '\0'){
		*dest = *scr;
		dest++;
		scr++;
	}
	*dest = '\0';
	return p;
} 
int main(){
	char *a=new char;
	*strcpy(a,"cvbnm");
	cout<<a<<endl;
	*strcpy(a,"asd");
	cout<<a;
	return 0;
} 

strcpy는 할당을 의미합니다. 알려진 문자열 값을 변수에 할당하고 변수 값을 출력합니다.

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
size_t strlen(const char *str){
	const char *cp = str;
	while (*cp++){
		;
	}
	return (cp-str-1);
}
int main(){
	cout<<strlen("abcdr")<<endl;
}

 

 이 함수의 구현은 모두 포인터 작업입니다! 어레이를 사용하여 구현할 수도 있지만 어레이의 저장 효율성은 낮아집니다.


4, 함수 및 포인터

4.1 함수 매개변수로서의 포인터

사용자 정의 함수의 매개변수는 정수 또는 부동 소수점 유형이 될 수 있는데 포인터 유형을 사용할 수 있나요?

그런 다음 포인터 매개변수를 사용하여 두 변수의 값을 교환해 보세요 .

예시 1. 두 값을 교환하고 비교합니다.

#include<iostream>
#include<cstdio> 
using namespace std;
void swap(int *x,int *y){ //交换两个值 
	int t = *x;
	*x = *y;
	*y = t;
}
void sort(int *x,int *y,int *z){ 
	if(*x > *y) swap(x,y); //比大小 
	if(*x > *z) swap(x,z);
	if(*y > *z) swap(y,z);
} 
int main(){
	int a,b,c;
	scanf("%d%d%d",&a,&b,&c);
	sort(&a,&b,&c);
	printf("a=%d,b=%d,c=%d",a,b,c);
	return 0;
}


4.2 함수 반환 포인터

포인터를 함수로 사용합니다(예: int *a(int a, int b)).

Recipe 1. n개의 정수를 포함하는 배열에서 첫 번째 소수를 찾아, 있으면 함수의 주소를 반환하고, 없으면 NULL을 반환한다.

#include<iostream>
#include<cstdio> 
#include<cmath>
using namespace std;
int n,a[1000];
bool isprime(int n){//求质数 
	if (n<2) return false;
	if(n==2) return true;
	for(int i=2;i<=sqrt(n);i++){
		if(n%i==0){
			return false;
		}
	}	
	return true;
} 

int *find(){ //指针查找函数 
	for(int i=1;i<=n;i++){
		if(isprime(a[i])){
			return &a[i];
		}
	}
	return NULL;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	int *p = find();
	if(p != NULL){
		cout<<p<<" "<<*p;
	}
	return 0;
}


4.3 함수 포인터와 함수 포인터 배열

(1) 일반적으로 함수를 정의합니다: int test(int) 그런 다음 포인터 함수 int (*test)(int)로 변경합니다. 

다음과 같이 작성할 수 없습니다:  int *test (int); 이런 방식으로 프로그래밍에서는 test(int)로 정의된 함수를 선언하고 반환 유형은 int *입니다.

(2) 함수의 주소를 구합니다. 배열과 마찬가지로 함수 이름도 주소이고, 함수 이름도 포인터로 간주할 수 있습니다.

1. typedef를 사용하여 함수 포인터 유형을 선언합니다.

#include<iostream>
#include<cstdio> 
using namespace std;
//函数指针 
int sum(int a,int b){
	return a+b;
} 
typedef int (*LP)(int,int); 
//定义声明了LP类型的函数指针,内有2个参数。
int main(){
	LP p = sum; // 定义LP类型的指针p 
	cout<<p(2,5); //函数指针p调用参数
	return 0;
}

  

 2. 시뮬레이션 메뉴 기능 구현 예, 함수 포인터 배열

//函数指针数组 
void t1(){	cout<<"test1"<<endl; } 
void t2(){	cout<<"test2"<<endl; } 
void t3(){	cout<<"test3"<<endl; } 
void t4(){	cout<<"test4"<<endl; } 
typedef void(*Tp)();
定义声明了空类型的函数指针 Tp,无参数。
int main(){
	Tp a[] = {t1,t2,t3,t4}; 
 定义TP类型的函数指针数组a 
	int x;
	cin>>x;
	a[x](); 
	return 0;
}


4.4 구조 포인터 

  1. 이름, 성별, 등급 구성원으로 구조를 정의합니다.
  2. 구조를 선언하고 값을 할당하며 구조 포인터도 선언합니다.
#include<iostream>
#include<cstdio> 
using namespace std;
struct Student{
	char name[20];
	char sex;
	float score;
};

Student *p;
Student stu={"lisi",'m',95.5};
  1. 3. 포인터 액세스 구조 멤버 방법:
  • (*포인터 이름).멤버 이름   (*p).이름
  • 포인터 이름->멤버 이름  p->이름
int main(){
	cout<<stu.name<<endl;
	p = &stu; //指针指向stu地址 
	cout<<(*p).name<<endl;
//	(*p).name 效果等同 stu.name
	cout<<(*p).sex<<endl;
	cout<<p->score; 
//	p->score 效果等同(*p).score
	return 0;
} 

 일반적으로 구조체 변수를 참조하기 때문에 구조체 전체를 참조하는 경우가 많아 비효율적이므로 일반적으로 포인터를 사용하면 쓰기 효율이 좋아진다.

추천

출처blog.csdn.net/weixin_44775255/article/details/129397866