c++返回指針的函數應用於求素數的實例

函數體內,return語句的表達式的值必須是地址值這是c++返回指針的函數關鍵

比如求素數的例子

<span style="font-size:24px;">// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <IOSTREAM>
#include <MATH.H>
using namespace std;
int k;
int* prime(int*p, int m, int* q);
int main(int argc, char* argv[])
{
	int a[10] = { 23, 12, 59, 48, 16, 31, 27, 19, 9, 87}, b[10];
	int n = 10, *p = b;
	for (int i = 0; i< n; ++i)
	{
		cout<<a[i]<<" ";
	}
	cout<<endl;
	p = prime(a, 10, p);
	for (i = 0; i < k; ++ i)
	{
		cout<<*p++<<" ";
	}
	printf("Hello Worl;d!\n");
	return 0;
}
int* prime(int*p, int m, int* q)
{
	int* w, i, j, flag, *q1 = q;
	for (i = 0; i < m; ++i)
	{
		flag = 1;
		w = p + i;
		for ( j = 2; j <= sqrt(*(p+i)); ++j)
		{
			if (*w % j == 0)
			{
				flag = 0;
			}
		}
		if (flag)
		{
			*q++ = *w;
			k++;
		}
	}
	return q1;
}
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章