我一直在尝试运行这段代码并不断出现分段错误,但数组确实打印出来了。 我到底做错了什么? 我相信问题主要出在函数的格式或我在函数中输入的参数上,我尝试了很多方法,但我尝试过的方法似乎都不起作用。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fillArray(int arr[], int arr_size);
void printArray(int arr[], int arr_size);
void fMin(int arr[], int arr_size, int *q);
void fMax(int arr[], int arr_size, int *p);
void fSum(int arr[], int arr_size, int *x);
int main(int argc, char *argv[])
{
int *arr=NULL;
int arr_size = atoi(argv[1]);
arr = malloc(arr_size * sizeof(int));
if(argc <= 2)
{
printf("ERROR: invalid command line args");
printf("Expecting: EXCECUTABLE <SIZE>");
}
fillArray(arr, arr_size);
int i;
for(i=0; i<arr_size; i++)
{
printf("argv[%d] - %2d", arr_size, arr[i]);
printf("\n");
}
printArray(arr, arr_size);
int *min, *max ,avg, sum;
int *p;
int *q;
int *x;
avg = sum / arr_size;
fMax(arr, arr_size, p);
fMin(arr, arr_size, q);
fSum(arr, arr_size, &sum);
printf("Max: %3d Pos: %3d \n", *max, *p);
printf("Min: %3d Pos: %3d \n", *min, *q);
printf("Sum: %3d \n", *x);
printf("Avg: %3d \n", avg);
//for realloc! printArray(arr, arr_size);
free(arr);
return 0;
}
void fillArray(int arr[], int arr_size)
{
srand(time(NULL));
int i;
for(i=0; i<arr_size; i++)
{
arr[i] = rand() % 101;
}
}//good!
void printArray(int arr[], int arr_size)
{
int i = 0;
printf(" POS | VAL \n");
printf("-----------\n");
for(i=0; i<arr_size; i++)
{
printf(" %3d | %3d \n", i, arr[i]);
}
}//good!
void fMin(int arr[], int arr_size, int *q)
{
int i;
int *min=NULL;
min=&arr[i];
for(i=1; i<arr_size; i++)
{
if(arr[i] < *min)
{
min = &arr[i];
q = &i;
}
}
}//cant null pointer
void fMax(int arr[], int arr_size, int *p)
{
int i;
int *max=NULL;
max = &arr[i];
for(i=1; i<arr_size; i++)
{
if(arr[i] > *max)
{
max = &arr[i];
p = &i;
}
}
}//good?
void fSum(int arr[], int arr_size, int *x)
{
int i;
int sum = *x;
for (i=0; i<arr_size; i++)
{
*x = i + arr[i];
}
}//what the heckie goin on here
我跑"./a.out 5 6"
它输出:
argv[5] - 31
argv[5] - 13
argv[5] - 27
argv[5] - 83
argv[5] - 23
POS | VAL
-----------
0 | 31
1 | 13
2 | 27
3 | 83
4 | 23
zsh: segmentation fault ./a.out 5 6