如何在堆区申请空间

利用new 关键字

语法:new 数据类型

#include<iostream>
using namespace std;
//如何在堆区申请空间 
int main()
{
	//语法:new 数据类型
	//利用new创建的数据,返回数据类型对应的指针
	 
	int *num=new int; 
	*num=100;
	cout<<*num<<endl; 
	delete num; //释放指针所指的那块堆区内存 
	 
	 //利用new开辟数组
	 int *arr=new int[10];	//10表示数组元素个数 
	 for(int i=0;i<10;i++)
	 	arr[i]=i+1;
	for(int i=0;i<10;i++)
		cout<<arr[i]<<endl;
	delete [] arr;	//释放数组时,必须加上[],表示释放的是数组 
	system("pause");
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是代码: #include <stdio.h> #include <stdlib.h> #include <string.h> // 商品结构体 typedef struct { char name[50]; float price; int quantity; } Product; void allocateMemory(Product **p, int n) { // 在堆区申请空间 *p = (Product*) malloc(n * sizeof(Product)); } void inputProducts(Product *p, int n) { // 输入商品信息 for (int i = 0; i < n; i++) { printf("商品 %d 的信息:\n", i + 1); printf("名称:"); scanf("%s", (p+i)->name); printf("单价:"); scanf("%f", &(p+i)->price); printf("个数:"); scanf("%d", &(p+i)->quantity); } } void calculateTotalPrice(Product *p, int n) { // 计算商品总价格 float total = 0; for (int i = 0; i < n; i++) { total += (p+i)->price * (p+i)->quantity; } printf("商品总价格:%f\n", total); } void calculateMostExpensiveProduct(Product *p, int n) { // 计算最贵的商品信息 float maxPrice = 0; int index = -1; for (int i = 0; i < n; i++) { if ((p+i)->price > maxPrice) { maxPrice = (p+i)->price; index = i; } } printf("最贵的商品信息:\n"); printf("名称:%s\n", (p+index)->name); printf("单价:%f\n", (p+index)->price); printf("个数:%d\n", (p+index)->quantity); } void searchProduct(Product *p, int n) { // 输入一个商品名称,查找单价信息 char name[50]; int found = 0; printf("请输入商品名称:"); scanf("%s", name); for (int i = 0; i < n; i++) { if (strcmp(name, (p+i)->name) == 0) { printf("%s 的单价是:%f\n", name, (p+i)->price); found = 1; break; } } if (!found) { printf("%s 不存在!\n", name); } } void sortProducts(Product *p, int n) { // 实现商品按单价排序 for (int i = 0; i < n-1; i++) { for (int j = i+1; j < n; j++) { if ((p+i)->price > (p+j)->price) { Product temp = *(p+i); *(p+i) = *(p+j); *(p+j) = temp; } } } printf("排序后的商品列表:\n"); for (int i = 0; i < n; i++) { printf("商品 %d:\n", i + 1); printf("名称:%s\n", (p+i)->name); printf("单价:%f\n", (p+i)->price); printf("个数:%d\n", (p+i)->quantity); } } void freeMemory(Product *p) { // 释放空间 free(p); } int main() { int n; printf("请输入商品数量:"); scanf("%d", &n); Product *products; allocateMemory(&products, n); inputProducts(products, n); calculateTotalPrice(products, n); calculateMostExpensiveProduct(products, n); searchProduct(products, n); sortProducts(products, n); freeMemory(products); return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值