C语言中没有new函数,但是有malloc函数
原型: void *malloc(unsigned int size);
#include<stdlib.h>或#include <malloc.h>
malloc 向系统申请分配指定size个字节的内存空间(连续的一块内存)。返回类型是 void* 类型。void* 表示未确定类型的指针。
malloc 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。
申请零字节内存,函数并不返回NULL,而是返回一个正常的内存地址,但是你却无法使用这块大小为0的内存。
#include <stdio.h>
#include <conio.h>
int main(void)
{
int i,n;
char *buffer;
printf("How long do you want the string ?");
scanf("%d",&i);
buffer=(char *)malloc(i+1);
if (buffer == NULL)
{
exit(1);
}
for (n=0;n<i;n++)
{
buffer[n]=rand()%26+'a'; /*generate 0-25 */
}
buffer[i]='\0';
printf("Random string :%s\n",buffer);
free(buffer);
getch();
return 0;
}
c++中有new函数
new可用来生成动态无名变量。
使用完动态无名变量后应该及时释放,要用到 delete 运算符。
int *p=new int [10]; //动态数组的大小可以是变量或常量;