程序设计与算法三一单元

第一题没问题

第二题:有点卡壳,主要凭记忆写出来的,要多练习下

第三题没问题

第四题没写出来

二:

填空,使得程序输出指定结果

#include <iostream>
using namespace std;
// 在此处补充你的代码
getElement(int * a, int i)
{
	return a[i];
}
int main()
{
	int a[] = {1,2,3};
	getElement(a,1) = 10;
	cout << a[1] ;
	return 0;
}
#include <iostream>
using namespace std;
int &
getElement(int * a, int i)
{
	return a[i];
}
int main()
{
	int a[] = {1,2,3};
	getElement(a,1) = 10;
	cout << a[1] ;
	return 0;
}

四:参考:

https://blog.csdn.net/Yichuan_Sun/article/details/79637186

填空,使得程序输出指定结果

#include <iostream>
using namespace std;

int main()
{
	int * a[] = {
// 在此处补充你的代码
};
	
	*a[2] = 123;
	a[3][5] = 456;
	if(! a[0] ) {
		cout << * a[2] << "," << a[3][5];
	}
	return 0;
}
#include <iostream>
using namespace std;

int main()
{
    int * a[] = {NULL,NULL,new int[1],new int[6]};
    *a[2] = 123;
    a[3][5] = 456;
    if(! a[0] ) {
        cout << * a[2] << "," << a[3][5];
    }
    return 0;
}

首先确定a是个指针数组,里面的元素都是指针或者地址。然后看到*a[2],那么a[2]肯定是一个指针或者内存空间。既然要输入一个值,那我们就给a[2]分配一个int空间。再然后看到a[3][5],因此我们刚开始认为a是个二维指针数组,但是那样写起来太麻烦了。于是我们把a[3]看成a中一段连续的空间,其中的第5个元素需要赋值,所以至少需要分配内存给它。所以我分配了6个int型的空间给a[3],问题解决。

注意,从这个问题可以学到,在数组初始化时的大括号里,我们可以用到new函数。

猜你喜欢

转载自blog.csdn.net/qq_31647835/article/details/81089247