嘿,我正在尝试使用函数和指针打印数组中的最大元素。下面是我的代码,但它的打印垃圾值。请帮忙。
void findmax(int arr[],int,int*);
void findMax(int arr[], int n, int* pToMax)
{
if (n <= 0)
return; // no items, no maximum!
int max = arr[0];
pToMax = &arr[0];
for (int i = 1; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
pToMax = (arr+i);
}
}
}
int main()
{
int nums[4] = { 5, 3, 15, 6 };
int *ptr;
findMax(nums, 4, ptr);
printf("The maximum is at address %u\n", ptr);
printf("It's at index %d\n",ptr - nums);
printf("Its value is %d\n", *ptr);
}