这个内存分配
int* array = malloc(n);
为 n 类型为 int 的元素的数组分配的内存不足,您必须编写
int* array = malloc( n * sizeof( int ) );
参数也应该是无符号整数类型。否则用户可以传递一个负整数,这将导致未定义的行为。
最好将参数声明为具有size_t 类型。是函数malloc的参数类型。
函数应该做一件事:分配和初始化一个数组。如果函数没有返回空指针,则由函数的调用者决定是否输出数组。
所以函数看起来像
int * create( size_t n )
{
const int MAX_VALUE = 100;
int *array = malloc( n * sizeof( int ) );
if ( array != NULL )
{
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < n; i++ )
{
array[i] = rand() % MAX_VALUE + 1;
}
}
return array;
}
这是一个演示程序。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int * create( size_t n )
{
const int MAX_VALUE = 100;
int *array = malloc( n * sizeof( int ) );
if ( array != NULL )
{
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < n; i++ )
{
array[i] = rand() % MAX_VALUE + 1;
}
}
return array;
}
int main(void)
{
size_t n = 0;
printf( "Enter the size of an array: " );
scanf( "%zu", &n );
int *array = create( n );
if ( array != NULL )
{
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", array[i] );
}
putchar( '\n' );
}
free( array );
return 0;
}
它的输出可能看起来像
Enter the size of an array: 10
75 36 30 75 53 49 42 52 61 9
虽然最好以用户可以自己确定最大值的方式声明函数。那就是函数看起来像
int * create( size_t n, int max_value )
{
int *array = malloc( n * sizeof( int ) );
if ( array != NULL )
{
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < n; i++ )
{
array[i] = rand() % max_value + 1;
}
}
return array;
}