Please for this bug////

Hi
The question asks that The one-dimensional array A of integers is given. Increase by 2 each its non-negative element.
I made this program but compiler says "variably modified 'h' at file scope" .
Please help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <stdio.h>
int n;
int h[n];
int a;

int main(int argc, char *argv[])
{
    scanf("%d",&n);
  for(a=1;a<n;a++)
  {
  scanf("%f",&h[a]);
}
for(a=1;a<n;a++)
{
    a=a+2;

printf("%d",a); }
system("pause");
  getchar();	
  return 0;

}
Last edited on
int n; n needs a value const int N = 10;
Last edited on
thank you but the problem says we should define number' n' ourselves in cmd
Then you'll need to dynamically allocate the memory for your array once the user has input it. You can't tell the compiler to create the array without knowing how long it is first.
so how can I do it?
After the user inputs the size, dynamically allocate the memory for the array.
What he is saying is do this.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    int n = 0;
    int *h = nullptr;
    
    std::cout << "Please enter the size of n: ";
    std::cin >> n;
   
    h = new int[n];
}
Thank you very much)
The philosophical question is, should the simple examples simply spit out new, or should they remind about resource management and input validation too? Hence, a (futile) variation (since STL has containers too):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <memory>

int main()
{
    int n = 0;
   
    std::cout << "Please enter the size of n: ";
    if ( std::cin >> n && 0 < n )
      {
        std::unique_ptr<int[]> h( new int[n] );
      }
    return 0;
}



Back to the original code:
1. Integer array, but input uses "%f".

2. Array indexing starts from 0, not 1. If I say that n=3, then the valid indices in your loop are {1,2}, which is not three items. {0,1,2} contains three items.

3. Within the "add 2, if non-negative" loop you do increase the loop counter by 3 on every iteration. The intention is probably to modify array elements, and only those array elements, whose value is non-negative.
Topic archived. No new replies allowed.