【问题标题】:Passing 2-D array to function gives strange error将二维数组传递给函数会产生奇怪的错误
【发布时间】:2015-02-19 21:03:07
【问题描述】:

您好,我正在尝试创建一个函数,但它给出了错误

  [Error] cannot convert 'float (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]' to 'float (*)[30]' for argument '1' to 'float vecino_mas_cercano(float (*)[30])'

我的代码是:

#include <iostream>
#include<stdio.h>
#include <fstream>
#include<stdlib.h>
using namespace std;

int n1=30;

float nearest_neighbor(float distances[30][30])
{  float min=distances[0][1];
   int candidates[n1];
   int city=0;

   for (int i=0;i<n1;i++)
   {  candidates[i]=i;
   }

   for (int i=0;i<n1;i++)
   {  for (int &j:candidates)
      {  if (j!=0)
            if (distances[city][j]<min);
            {  min=distances[i][j];
               candidates[i]=0;
               city=j;
            }
      }
   }
   return min;
}

int main()
{
   //Declaración de variables

   int n=30; //número de nodos o cityes


   FILE *d;
   float distance[n][n];
   d =fopen("Oli30.csv","r");//r abrir el archivo que contiene las distances para leerlo

   for(int i=0 ;i<n; i++) //en la matriz distance se guardan los valores de las distances
   {  for(int j=0; j<n; j++)
      {  fscanf(d,"%f",&distance[i][j]);}
   }

   float tau_initial;

   tau_initial=nearest_neighbor(distance);  
   cout << "The result is " << tau_initial;
   return 0;

}

我想问题是因为距离被设置为一个指针,我不知道如何在函数nearest_neighbor 中传递这个参数。

有人可以解释一下如何使它工作吗??

谢谢

【问题讨论】:

  • float[30] 是与float[31] 完全不同的类型。记住这一点,编译器应该如何将 float[30][30] 的参数与边界取决于运行时整数(不是标准 C++)的参数匹配?
  • 请注意float nearest_neighbor(float distances[30][30])的函数签名是float nearest_neighbor(float distances**)
  • 避免变长数组编译器扩展的另一个原因。
  • 如果您真的致力于 C++,您可能想要使用标准库容器。 C 风格的数组受到更多限制。
  • OT, if (distances[city][j]&lt;min); 在那个位置用分号有点没用。

标签: c++ arrays function pointers


【解决方案1】:

int n = 30; 必须更改为 int const n = 30;

正如你现在所拥有的,float distance[n][n] 是非法的。标准 C++ 中的数组必须具有维度常量。

错误消息表明您的编译器正在为具有非常量维度的数组实现某种扩展(可能类似于 C VLA),然后它不知道如何将其与需要数组的函数匹配尺寸不变。

【讨论】:

  • 编译时常量,甚至
  • @BenVoigt 是的,用精确的语言指定有点棘手。在int x[30] 中,30 不是const,但它是一个常量表达式,正如您所说,某些常量表达式不合格。随意编辑:)
  • int n1=30;同样的问题
【解决方案2】:

我相信你这里有一个无意的错误:

     if (distances[city][j]<min); // The if block ends here.
     {  min=distances[i][j];
        candidates[i]=0;
        city=j;
     }

你的意思可能是:

     if (distances[city][j]<min)
     {
        min=distances[i][j];
        candidates[i]=0;
        city=j;
     }

【讨论】:

    【解决方案3】:

    问题可以通过将main中的nearest_neighbordistance的参数类型改为float**来解决。但是,distance 的初始化必须以不同的方式进行,实际尺寸应作为参数传递给nearest_neighbor

    【讨论】:

    • 如果从文件中读取实际矩阵大小,这将是一种有用的方法......但在这种情况下,文件格式显然具有固定大小。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多