我正在编写 ac 程序,我注意到每当我用 const 变量(const size_t MAX_LEN = some number)声明我的数组长度时,它都会向我发送错误。另一方面,当我使用 (#define MAX_LEN = some number ) 作为我的数组长度声明时,它工作得很好。
我得到的确切错误: LinSeperator.c:45:2: 错误:使用可变长度数组 'arr' [-Werror=vla] double theAns, arr[MAX_LEN]; ^
谁能帮我弄清楚为什么会这样?
编辑:这是我的代码:这是我的 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[]);
Run Code Online (Sandbox Code Playgroud)
这是我的 .c 文件:
#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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 C 中,const
不要创建编译时常量。它只是创建一个只读变量。区别很重要。
当您使用:
#define MAX_LEN 701
Run Code Online (Sandbox Code Playgroud)
这是给预处理器的指令,用于替换所有出现的MAX_LEN
with 701
。当编译器获取您的代码时,它所看到的只是数值常量。
C 90 标准只允许声明具有数字常量长度的数组。但是,如果要使用 C 99,则可以使用可变长度数组。
使用gcc
,您可以使用--std=c99
或--std=c90
设置编译代码所依据的标准。