error: expected expression before { token
#include <stdio.h>
int main() {
int t;
scanf("%d",&t);
while(t-->0){
int m,n,a,b,k;
int *arr;
scanf("\n%d %d",&n,&m);
arr[n]={ };
for(int i=0;i<m;i++){
scanf("\n%d %d %d",&a,&b,&k);
int max=arr[0];
for(int i=a;i<=b;i++){
arr[i]=arr[i]+k;
if(arr[i]>max){
max=arr[i];
}
}
printf("%d\n",max);
}
}
return 0;
}
in this code, I am initializing the array to zero but it is not working and if I do this also arr[n]={} or declare the array global then also I got the error.
Because n
is defined as a variable, there are two problems with the following statement:
int arr[n]={ };
The error on my system states
error: use of GNU empty initializer extension
If this were not a VLA, the problem could be addressed by providing an initializer:
#define n 10 //used to size a non-VLA array
...
int arr[n]={0}; //Uses constant array size, not variable, thus can be initialized normally.
But it is a VLA, leading to the next issue, incorrect use of VLA, where the error states:
error: variable-sized object may not be initialized
Both issues can be addressed with following:
int arr[n];
memset(arr, 0, sizeof(arr));
One final suggestion is to check the return value for the scanf() statement:
scanf("\n%d %d",&n,&m);
To ensure the correct number of items have been processed before assuming n
.
int count = scanf("\n%d %d",&n,&m);
if(count == 2)
{
int arr[n];
memset(arr, 0, sizeof(arr);
....