1. 程式人生 > >C語言函式的指標小練習

C語言函式的指標小練習

總時間限制: 

1000ms

 

記憶體限制: 

65536kB

// 在此處補充你的程式碼

描述

程式填空,使得輸出結果為:

1,4,9,16,25, 
h,e,l,l,o,!,

#include <iostream>
using namespace std;

void ForEach(void * a, int width, int num,
)

{
	for(int i = 0;i < num; ++i) 
		f((char*)a+width*i);
}

void PrintSquare(void * p)
{
	int * q = (int*)p;
	int n = *q;
	cout << n * n << ",";
}
void PrintChar(void * p) {
	char * q = (char*)p;
	cout << *q << ",";
}
int main()
{
	int a[5] = {1,2,3,4,5};
	char s[] = "hello!";
	ForEach(a,sizeof(int),5,PrintSquare); 
	cout << endl;
	ForEach(s,sizeof(char),6,PrintChar);
	return 0;
}

輸入

輸出

1,4,9,16,25,
h,e,l,l,o,!,

樣例輸入

樣例輸出

1,4,9,16,25,
h,e,l,l,o,!,

來源

Guo Wei

 

#include <iostream>
using namespace std;

void ForEach(void * a, int width, int num,void f(void* p)
	// 在此處補充你的程式碼
	)

{
	for (int i = 0; i < num; ++i)
		f((char*)a + width * i);
}

void PrintSquare(void * p)
{
	int * q = (int*)p;
	int n = *q;
	cout << n * n << ",";
}
void PrintChar(void * p) {
	char * q = (char*)p;
	cout << *q << ",";
}
int main()
{
	int a[5] = { 1,2,3,4,5 };
	char s[] = "hello!";
	ForEach(a, sizeof(int), 5, PrintSquare);
	cout << endl;
	ForEach(s, sizeof(char), 6, PrintChar);
	return 0;
}