0

What's wrong

#include <iostream> using namespace std; int main() { int n; cin>>n; //size of the array int *p=NULL; p=new int nums [n]; for (int j=0; j<n; j++){ j=nums[n]; } int max = nums[0]; for(int i=0; i<n; i++) { if(nums[i]>max) max = nums[i]; } cout << max; return 0; }

5th Jun 2021, 1:45 PM
Vladimir Kushner
Vladimir Kushner - avatar
5 ответов
+ 5
You don't give an extra name when allocating memory, you access it through the pointer. The line p = new int nums [ n ]; is invalid syntax and should just be p = new int [ n ]; You then have to access that array through the pointer 'p', or rename the pointer itself "nums". Furthermore, the task expects you to get the array values from the input stream, but your first for loop does something entirely else. Use std::cin to get each element from the user. Also, you forgot to free the allocated memory at the end. While not so important in this example, it is definitely bad practice.
5th Jun 2021, 2:18 PM
Shadow
Shadow - avatar
+ 4
The line `p = new int nums[n]` is invalid syntax. "nums" can't be put there. If you want the name of the allocated array to be `nums`, change the variable name (`p`) to `nums` ``` int *nums = new int[n]; // now nums can be used to access the allocated memory ``` If you're confused with the syntax, revisit the lesson on memory allocation See last section of lesson 33.1
5th Jun 2021, 2:17 PM
XXX
XXX - avatar
+ 4
Memory part as Shadow and XXX explained. There is one more thing: j = nums[n] should be cin >> nums[j]
5th Jun 2021, 2:22 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
Program must find the largest value in to array.
5th Jun 2021, 1:48 PM
Vladimir Kushner
Vladimir Kushner - avatar
0
👍 excellent explanation
5th Jun 2021, 7:27 PM
Vladimir Kushner
Vladimir Kushner - avatar