开启辅助访问 天气与日历 切换到宽版

 找回密码
 立即注册

微信帐号登录

简单一步,快速登陆

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 1720|回复: 0

如何创建一个动态数组

[复制链接]

16

主题

31

回帖

233

积分

管理员

积分
233
发表于 2024-1-11 22:36:57 | 显示全部楼层 |阅读模式 美国
#include <iostream>

/**
 * @brief  This is the test for new and delete operator. And create a dynamic array.
 * 
 * @return int 
 */

int main() {
    using namespace std;
    int* pNumber = new int;
    int * pNumber2 = pNumber;
    delete pNumber2;
    //delete pNumber; // We can not delete the same memory again, because it is already deleted.
    cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point: six decimal places
    cout << "Please the size of array:";
    int n = 0;
    cin >> n;
    double* arr = new double[n];
    for (int i = 0; i < n; i++) {
        cout << "Please enter number" << i << ": ";
        cin >> arr[i];
    }
    double sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    cout << "Sum: " << sum << endl;
    cout << "Average: " << sum / n << endl;
    delete [] arr;
    return 0;
}

The main.cpp file contains a C++ program that creates a dynamic array and performs some operations on it. Here's a step-by-step explanation:

  1. The main function starts by declaring a pointer pNumber and allocating memory for an integer using the new operator.
int* pNumber = new int;
  1. Another pointer pNumber2 is declared and assigned the same memory address as pNumber.
int * pNumber2 = pNumber;
  1. The memory allocated to pNumber2 is then deallocated using the delete operator. Note that the same memory cannot be deleted again, hence the commented out delete pNumber;.
delete pNumber2;
  1. The program then sets the output format for floating point numbers to fixed-point with six decimal places.
cout.setf(ios_base::fixed, ios_base::floatfield);
  1. The program prompts the user to enter the size of an array, n, and creates a dynamic array arr of size n.
cout << "Please the size of array:";
int n = 0;
cin >> n;
double* arr = new double[n];
  1. The program then prompts the user to enter n numbers, which are stored in the array arr.
for (int i = 0; i < n; i++) {
    cout << "Please enter number" << i << ": ";
    cin >> arr[i];
}
  1. The program calculates the sum of the numbers in the array and prints it out. It also calculates the average of the numbers and prints it out.
double sum = 0;
for (int i = 0; i < n; i++) {
    sum += arr[i];
}
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / n << endl;
  1. Finally, the program deallocates the memory allocated to the array arr using the delete[] operator and returns 0, signaling successful execution of the program.
delete [] arr;
return 0;

This program demonstrates the use of dynamic memory allocation in C++, as well as basic input/output and arithmetic operations.

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋| 怪异的C语言

GMT+8, 2024-10-1 19:13 Powered by Discuz! X3.5