【发布时间】:2016-07-29 08:31:30
【问题描述】:
我正在编写一个 c 程序,我注意到每当我用 const 变量(const size_t MAX_LEN = some number)声明我的数组长度时,它都会向我发送错误。 另一方面,当我使用 (#define MAX_LEN = some number) 作为我的数组长度声明时,它工作得很好。
我得到的确切错误:LinSeperator.c:45:2: error: variable length array ‘arr’ is used [-Werror=vla] 加倍答案,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[]);
这是我的 .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]);
}
}
}
【问题讨论】:
-
您能尝试创建一个Minimal, Complete, and Verifiable Example 并展示给我们看吗?并且还包括 complete 错误输出?
-
尝试添加
-std=c99选项。 -
您的编译器是否符合 c99 c 标准?因为可变长度数组 (VLA) 仅在 c99 中添加
-
显示你的代码而不是描述它。
-
"
#define MAX_LEN = some number" 很可能无法编译。你想删除=。