[英]ISO C++ forbids variable-size array (compilation error)
通常我總是這樣編譯我的C代碼:g ++ program.c -o program.exe
但我的大學教授要求我編譯使用:g ++ -o -Wall -Wextra -Werror -pedantic -std = c ++ 0x program.exe program.c
(這對我來說是新的)。
所以......我運行命令並得到以下錯誤:
eda.c: In function ‘int main()’:
eda.c:200: error: ISO C++ forbids variable-size array ‘v’
eda.c:207: error: ISO C++ forbids variable-size array ‘nfloat’
cc1plus: warnings being treated as errors
eda.c:215: warning: suggest a space before ‘;’ or explicit braces around empty body in ‘while’ statement
這是我的程序的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct {
float* data;
int size;
} vector;
/* Metodos Básicos */
vector *create_vector(int n, float* comps){
vector *newvect = (vector*)malloc(sizeof(*newvect));
newvect->data = (float*)malloc(n*sizeof(float));
memcpy(newvect->data, comps, sizeof(float) * n);
newvect->size = n;
return newvect;
}
void destroy_vector(vector* v){
free(v->data);
free(v);
}
void print(vector* v){
int size = v->size, i;
for (i = 0; i < size; ++i)
{
if(i == 0) printf("[%.1f,", v->data[i]);
else if(i == (size-1)) printf("%.1f]\n", v->data[i]);
else printf("%.1f,", v->data[i]);
}
}
/* Metodos Intermedios */
float dotDiferentSizes(vector* v1, vector* v2, int smax, int smin){
double product;
int i;
for(i = 0; i < smin; i++){
product += (v1->data[i])*(v2->data[i]); // += means add to product
}
for(i = smin; i < smax; i++){
product += (v1->data[i])*0; // += means add to product
}
return product;
}
float dot(vector* v1, vector* v2){
int smax = (v1->size), smin;
int v1size = smax;
int v2size = (v2->size);
float product = 0.0;
if (v2->size > smax) {
smax = v2->size; //max_size checking
smin = v1->size; //min_size checking
}
else if (v2->size < smax){
smin = v2->size;
}
else smin = smax;
// compute
if(smax == smin){
int i;
for(i = 0; i < smin; i++){
product += (v1->data[i])*(v2->data[i]); // += means add to product
}
}
else{
if(v1size == smax){
product = dotDiferentSizes(v1,v2,smax,smin); //v1>v2
}
if(v2size == smax){
product = dotDiferentSizes(v2,v1,smax,smin);
}
}
return product;
}
float norm(vector* v){
int size = v->size, i;
float norm = 0.0;
for(i= 0; i < size; i++){
norm += (v->data[i])*(v->data[i]);
}
norm = sqrt( norm );
return norm;
}
void normalize(vector* v){
int size = v->size, i;
float norma = 0.0;
norma = norm(v);
for(i= 0; i< size; i++){
v->data[i] = v->data[i] / norma;
}
for (i = 0; i < size; ++i)
{
if(i == 0) printf("NORMALIZED VECTOR:[%.2f,", v->data[i]);
else if(i == (size-1)) printf("%.2f]\n", v->data[i]);
else printf("%.2f,", v->data[i]);
}
}
/* Metodos Avanzados */
vector* add(vector* v1, vector* v2){
vector *vadd;
int v1size, v2size, i;
v1size = v1->size;
int size = v1size;
v2size = v2->size;
if(v2size > v1size) {
size = v2size;
vadd = create_vector(size, v2->data);
for(i = 0; i < v1size; i++){
vadd->data[i] += v1->data[i];
}
}
else {
vadd = create_vector(size, v1->data);
for(i = 0; i < v1size; i++){
vadd->data[i] += v2->data[i];
}
}
return(vadd);
}
vector* sub(vector* v1, vector* v2){
vector *vsub;
int v1size, v2size, i;
v1size = v1->size;
int size = v1size;
v2size = v2->size;
if(v2size > v1size) {
size = v2size;
vsub = create_vector(size, v2->data);
for(i = 0; i < v1size; i++){
vsub->data[i] = v1->data[i] - vsub->data[i]; /* restamos siempre v1 - v2*/
} /* en el bucle forzamos a restar v1 - v2, evitando el caso v2 - v1*/
for(i = v1size; i < size; i++){
vsub->data[i] = (v2->data[i])*(-1);
}
}
else { /* v1size >= v2size */
vsub = create_vector(size, v1->data);
for(i = 0; i < v2size; i++){
vsub->data[i] -= v2->data[i];
}
}
return(vsub);
}
void incr(vector* source, vector* other){
int smax, i, ssize = source->size, osize = other->size;
vector *vincr;
if(ssize > osize) smax = ssize;
else {
if(ssize < osize) smax = osize;
else smax = ssize;
}
vincr = add(source, other);
if(ssize > osize){
for(i = 0; i < smax; i++){
source->data[i] = vincr->data[i];
}
}
else{
source->data = (float*)realloc(source->data, sizeof(float) * smax);
source->size = smax;
for(i = 0; i < smax; i++){
source->data[i] = vincr->data[i];
}
}
print(source);
free(vincr);
}
//NumsVector, funcion que nos devuelve el numero de "numeros" que hay en cada vector del .txt,
//es decir, los n floats por cada vector
int NumsVector(char *linea, ssize_t size){
int numsvector = 1; //Inicializamos a 1 ya que no podemos suponer valor maximo segun enunciado, pero si minimo >= 1
int n;
for(n = 2; n<= size; n++){ //como ya suponemos que el primer valor despues del corchete es un numero y ya lo hemos contado, empezamos en 2
if (linea[n] != '[' && linea[n] != ']'){
if(linea[n] == 44){
numsvector = numsvector + 1;
}
}
}
return numsvector;
}
int main(){
int n, i;
scanf("%d\n", &n);
vector *v[n];
for(i = 0; i<n; ++i) {
char *line = NULL; //ponemos *line y len a valores 0 y null para que automaticamente getline nos haga el malloc y nos asigne el tamanyo
size_t len = 0;
ssize_t read; //en la variable read guardamos el valor de getline, contiene el numero de caracteres que tiene el string
read = getline(&line,&len,stdin);
int numsvector = NumsVector(line, read);
float nfloat[numsvector]; //sabemos el tamanyo del vector que hemos leido, creamos array de floats y lo llenamos de los floats
//empieza el proceso para obtener los floats a partir de string de chars
int j = 0;
line[strlen(line) - 1] = ','; /* Replaces the end ] with a , */
char *p = line + 1; /* creates a new pointer, pointing after the first [ in the original string */
do
{
sscanf(p, "%f,", &nfloat[j]); /* grabs up to the next comma as a float */
while (*(p++) != ',') ; /* moves pointer forward to next comma */
}
while (++j < numsvector); /* stops when you've got the expected number */
v[i] = create_vector(numsvector, nfloat);//conseguimos almacenar el contenido del string en un vector del tipo float (nfloat)
int aux;
for(aux = 0; aux<numsvector; ++aux){
printf("V[%d]->data[%d] = : %.1f\n", i, aux, v[i]->data[aux]); //test de que la memoria se almacena bien, luego se borra
}
free(line);
}
}
這些是給出錯誤的行:
200: vector *v[n];
207: float nfloat[numsvector];
215: while (*(p++) != ',') ; //Now I think works fine with the extra space..
請有人幫我編譯文件嗎?
問題是你正在使用的功能( 可變長度數組或VLA )是C99功能,不是C ++標准的一部分,但gcc
支持它作為擴展 , -pedantic
將強制gcc
在你使用擴展時警告你-Werror
會發出警告錯誤,這將有效地阻止您使用擴展。
如果你能夠使用C ++,一個選擇是使用std :: vector 。 另一種選擇是通過new
或malloc
使用動態分配,具體取決於您可以使用哪些。
這是一個有點古怪,它好像你必須用C編程,但使用C ++編譯器,我希望至少你可以使用-xc
使g++
作為C編譯器。 這篇文章涵蓋了C和C ++的兼容性 ,你也應該閱讀Keith的評論。
通常我總是這樣編譯我的C代碼:g ++ program.c -o program.exe
那是不對的。 g++
是一個C ++編譯器,而不是C編譯器。 (我知道,您可以指定-xc
來強制使用該語言,但是為什么在擁有C編譯器時也會這樣做?)
C代碼應該用C編譯器編譯。 C ++代碼應該用C ++編譯器編譯。 任何其他組合都是錯誤的。
如果您需要編寫C ++代碼,那么編寫C ++代碼。 在C ++中,您不能擁有C99樣式的可變長度數組。 您將需要使用std::vector
。 像這樣:
std::vector<some_type> theVector(initial_size);
200:vector * v [n]; 可以通過初始化向量來修復:
vector* v = new vector[n];
207:float nfloat [numsvector]; 可以通過動態分配數組來修復:
float* nfloat = new float[numsvector]
我相信這些是相應的C內存分配:
vector* v = malloc(n * sizeof(vector));
float* nfloat = malloc(numsvector * sizeof(float));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.