示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//malloc()、free()
#include <stdlib.h>
//argc: 参数个数 argv[]: 参数数组
//int main(int argc, char **argv)
int main(int argc, char *argv[])
{
double * ptd;
int max;
int number;
int i = 0;
puts("What is the maximum number of type double entries?");
if (scanf("%d", &max) != 1)
{
puts("Number not correctly entered -- bye.");
exit(EXIT_FAILURE);//程序异常中止
}
//动态分配内存
/*在C中,不一定要使用强制类型转换(double *),但是在C++中必须使用。
所以,使用强制类型转换更容易把C程序转换为C++程序。*/
ptd = (double *)malloc(max * sizeof(double));
if (ptd == NULL)
{
puts("Memory allocation failed. Goodbye.");
exit(EXIT_FAILURE);//程序异常中止
}
//EXIT_FAILURE表示异常中止
//EXIT_SUCCESS表示程序正常结束
//一些操作系统(包括UNIX、Linux和Windows)还接受一些表示
//其他运行错误的整数值.
/* ptd现在指向有max个元素的数组 */
puts("Enter the values (q to quit):");
while (i < max && scanf("%lf", &ptd[i]) == 1)
++i;
printf("Here are your %d entries:\n", number = i);
for (i = 0; i < number; i++)
{
printf("%7.2f ", ptd[i]);
if (i % 7 == 6)
putchar('\n');
}
if (i % 7 != 0)
putchar('\n');
puts("Done.");
//释放动态分配的内存
/*free()函数释放由malloc()分配的内存。free()只释放其参数指向的内存块。
一些操作系统在程序结束时会自动释放动态分配的内存,但是有些系统不会。
为保险起见,请使用free(),不要依赖操作系统来清理。
不能用free()释放通过其他方式(如,声明一个数组)分配的内存。*/
free(ptd);
system("pause");
return 0;
}
运行测试