i'm writing a c program and i've noticed that whenever i declare my array length with const variable(const size_t MAX_LEN = some number) it sends me errors. on the other hand, when i'm using (#define MAX_LEN = some number) as my array length declaration it works just fine.
the exact error i get : LinSeperator.c:45:2: error: variable length array ‘arr’ is used [-Werror=vla] double theAns, arr[MAX_LEN]; ^
could anyone help me figure out why it happens?
EDIT: here's my code: this is my LinSeperatorHelperFunc.h:
#pragma once
#include <stdio.h>
const size_t MAX_LEN = 199;
typedef struct Orange
{
double arr[MAX_LEN];
int tag;
}orange;
void learnProg(orange *o, double w[], int d);
void filePrinter(const char *output, FILE **fileIn, int d, double w[]);
this is my .c file:
#include "LinSeperator.h"
#include "LinSeperatorHelperFunctions.h"
#define NEG_ONE (-1)
#define NegToPos (2)
void LinSeperator(const char *In, const char *Out){
FILE * input;
orange o;
int d , pos, neg ,i , j;
//initializing the hypothesis vector as requested in step 1
double w[MAX_LEN];
for(i = 0 ; i<MAX_LEN ; i++){
w[i] = 0;
}
input = fopen(In,"r");
if(input == NULL){
printf("file doesnt exists");
return;
}
fscanf(input, "%d %d %d", &d , &pos, &neg);
for(i = 0; i<pos+neg ; i++){
o.tag = i<pos ? 1: -1;
for(j = 0 ; j<d ; j++){
fscanf(input, "%lf", &o.arr[j]);
//removing ',' from being scanned
if(j!= d-1){
fgetc(input);
}
}
learnProg(&o,w,d);
}
filePrinter(Out, &input, d, w);
fclose(input);
}
void filePrinter(const char* out, FILE **in, int d, double w[]){
int i;
double theAns, arr[MAX_LEN];
FILE *output = fopen(out, "w");
if (output == NULL){
printf("couldnt write to the current file");
return;
}
while(!feof(*in)){
for (i=0; i<d; i++) {
fscanf((*in), "%lf", &arr[i]);
if(feof(*in))//if we finished the checked vectors we should finish the file and the function
{
fclose(output);
return;
}
//preventing from reading the "," between each col
if(i!=d-1){
fgetc(*in);
}
}
theAns=0;
for (i=0; i<d; i++){
theAns+=arr[i]*w[i];
}
//if ans >=0 print 1 to file else -1
fprintf(output, "%d\n", NEG_ONE+NegToPos*(theAns>=0));
}
fclose(output);
}
//the learning progress algo
void learnProg(orange *o, double w[], int d){
int i, negOrPos = (*o).tag;
double theAns = 0;
for(i = 0; i<d ; i++){
theAns += ((*o).arr[i] * w[i]); //2.1
}
//has the same sign
if( (negOrPos * theAns) > 0 ){ //2.2
return ;
}
else{
for(i = 0; i<d ; i++){
w[i] += (negOrPos * (*o).arr[i]);
}
}
}
-std=c99option.#define MAX_LEN = some number" most likely won't compile. You want to remove the=.