1.#include <stdio.h>
#include <malloc.h>
int main()
{
int i = 0;
int* pI = (int*)malloc(5 * sizeof(int));
short* pS = (short*)calloc(5, sizeof(short));
for(i=0; i<5; i++)
{
printf("pI[%d] = %d, pS[%d] = %d
", i, pI[i], i, pS[i]);
}
pI = (int*)realloc(pI, 10 * sizeof(int));
for(i=0; i<10; i++)
{
printf("pI[%d] = %d
", i, pI[i]);
}
free(pI);
free(pS);
return 0;
}
2.#include <stdio.h>
#include <string.h>
struct Product
{
char name[128];
int price;
};
struct Product pro[1000];
struct Product sale;
void waitForSale()
{
printf("Record Product: ");
scanf("%s %d", sale.name, &sale.price);
}
int main()
{
int i = 0;
for(i=0; i<1000; i++)
{
waitForSale();
strcpy(pro[i].name, sale.name);
pro[i].price = sale.price;
printf("%s, %d
", pro[i].name, pro[i].price);
}
return 0;
}
@说明:
动态内存分配是CCC语言中的强大功能语言中的强大功能
程序能够在需要的时候有机会使用更多的内存
malloc单纯的从系统中申请固定字节大小的内存
calloc能以类型大小为单位申请内存并初始化为00
realloc用于重置内存大小