所以我在C中创建了一个动态数组。该数组只包含数字。如何扫描我创建的1D数组以打印多少个数字大于数组中的最后一个?我创建了仅扫描文件的代码,如下所示:
#include <stdio.h>
#include <limits.h>
int process( FILE *f ) {
int a, b;
static int total = 1;
if ( f == 0 ) return 0;
if ( fscanf( f, "%d", &a ) != 1 ) return INT_MIN;
if ( (b= check_file ( f )) == INT_MIN ) return a;
if ( a > b )
{total++; return printf( "%d > %d and total now is %d\n", a, b, total ), a; }
return b;
}
int main( void ) {
FILE *fp= fopen( "xxx.txt", "r" );
process( fp );
fclose( fp );
return 0;
}
我可以对阵列做同样的事吗?我怎样才能做到这一点?我应该使用哪些命令?
动态数组:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int t_size;
FILE * fp;
fp = fopen ("xxx.txt", "r");
fscanf(fp, "%d", &t_size);
printf("Create a size of %d array\n", t_size);
int* my_array = NULL;
my_array = malloc(t_size*sizeof(*my_array));
if (my_array==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 1; //return with failure
getchar();
}
int i =0;
for ( i = 0; i < t_size; i++ )
{
fscanf(fp, "%d",&my_array[i]);
}
//if all is working smoothly...
printf("All up and running! Array created! :D\n");
for(i = 0; i < t_size; i++ )
{
printf(" %d : %d\n", i, my_array[i]);
}
getchar();
free(my_array);
}
答案 0 :(得分:0)
你必须:
int arr[N]
,其中N
是元素的数量)arr[N-1]
)答案 1 :(得分:0)
#include <stdio.h>
#include <limits.h>
int process( int *array, int *endp) {
int a, b;
if ( array == 0 ) return 0;
if ( array == endp ) return INT_MIN;
else a = *array++;
if ( (b= process( array, endp )) == INT_MIN ) return a;
if ( a > b ) return printf( "%d > %d\n", a, b ), a;
return b;
}
int main( void ) {
int array[] = { 4, 3, 2, 1};
int t_size = 4;
process(array, array + t_size);
return 0;
}