I am facing a problem while initializing an array in C. I am trying to take input of a variable 'n' and declare an array marks[n] with its value set to zero. I wrote the following part of the program to do it.
int n,k,e,m,x;
scanf("%d %d %d %d", &n,&k,&e,&m);
int marks[n]={0};
but executing the program generates the following warnings and errors:
prog.c: In function ‘main’:
prog.c:10:6: error: variable-sized object may not be initialized
int marks[n]={0};
^~~
prog.c:10:20: warning: excess elements in array initializer
int marks[n]={0};
^
prog.c:10:20: note: (near initialization for ‘marks’)
This is the whole program:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int t;
scanf("%d",&t);
for (int z = 0; z < t; ++z)
{
int num_candidate,num_seat,num_exam,max_mark,mark_needed;
scanf("%d %d %d %d", &num_candidate,&num_seat,&num_exam,&max_mark);
int marks[num_candidate]={0};
/*gets the total marks of each students. mark of the last exam of the */
/*num_candidate-th student is not taken */
for (int i = 0; i < num_candidate; ++i)
{
for(int j=0;j<num_exam;j++)
{
if (i==num_candidate-1 && j==num_exam-1)
{
break;
}
scanf("%d",&mark_needed);
marks[i]=marks[i]+mark_needed;
}
}
/*sorting*/
for (int i = 0; i < num_candidat-2; i++)
{
for(int j=i; j<num_candidat-2; j++)
{
if (marks[j]<marks[j+1])
{
int temp = marks[j];
marks[j]= marks[j+1];
marks[j+1]=temp;
}
}
}
/*prints the needed marks*/
mark_needed=marks[num_seat-1]-marks[num_candidat-1];
printf("%d\n",mark_needed+1 );
}
return 0;
}
My goal is to take num_candidate=number of candidates, num_seat= number of seats in the school, num_exam=number of exams, max_mark=maximum achievable marks in a single exam. I want to know how many marks the n-th student would need in his final exam to be admitted. his mark of the last exam is not taken as an input in the program and I want to figure out the least marks he would need in the final exam.
How can I solve it?
From the C Standard (6.7.9 Initialization)
3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.
So instead of this declaration with an initializer
int marks[n]={0};
use
int marks[n];
memset( marks, 0, n * sizeof( int ) );
Pay attention to that n
may not be equal to zero.