c++ - 如何在 C++ 中返回结构数组?

标签 c++ arrays struct

错误是说: 'mypoint' 未在此范围内声明。

我的结构是

struct point
{
   int x;
   int y;
};

我的代码是:

struct point lineangle(int x1, int y1, int x2, int y2, int n){
    double angle=360/n, s,c;
    int rotated_x,rotated_y;
    DDA(x1,y1,x2,y2);
    for(int i=0;i<n;i++){
        c = cos(angle*3.14/180);
        s = sin(angle*3.14/180);

        rotated_x= (x1 +((x2-x1)*c-(y2-y1)*s));
        rotated_y= (y1 +((x2-x1)*s+(y2-y1)*c));

        struct point mypoint[]={};

        mypoint[i].x=x1;
        mypoint[i].y=y1;
        mypoint[i+1].x = rotated_x;
        mypoint[i+1].y = rotated_y;
//      DDA(x1,y1,rotated_x,rotated_y);
        x2=rotated_x;
        y2=rotated_y;
    }

    return mypoint;
}

我已声明但未检测到。

最佳答案

这里的问题是您在 for 循环的内部 声明mypoint,因此它超出了返回值的范围。尝试将声明移到 for 循环之前。

struct point mypoint[]={};
for(int i=0;i<n;i++){
  // ...
}
return mypoint;

当然,这不是您的代码的唯一问题。老实说,我不确定你到底想在这里做什么,但如果你在堆栈上声明一个数组,你还需要提供一个长度:

struct point mypoint[n + 1]={};
for(int i=0;i<n;i++){
  // ...
}
return mypoint;

mypoint 是一个struct point 数组,而不是单个struct point,但您返回的是单个struct point 。要么返回整个数组,要么返回你想要的元素:

struct point mypoint[n + 1]={};
for(int i=0;i<n;i++){
  // ...
}
return mypoint[0];

另一种可能性是你并不真的希望 mypoint 是一个数组,在这种情况下你应该将它声明为 struct point mypoint;(在环形)。也许像

struct point lineangle(int x1, int y1, int x2, int y2, int n){
    double angle=360/n, s,c;
    int rotated_x,rotated_y;
    struct point mypoint;
    DDA(x1,y1,x2,y2);
    for(int i=0;i<n;i++){
        c = cos(angle*3.14/180);
        s = sin(angle*3.14/180);

        rotated_x= (x1 +((x2-x1)*c-(y2-y1)*s));
        rotated_y= (y1 +((x2-x1)*s+(y2-y1)*c));

        struct point mypoint[]={};

        mypoint.x = rotated_x;
        mypoint.y = rotated_y;
//      DDA(x1,y1,rotated_x,rotated_y);
        x2=rotated_x;
        y2=rotated_y;
    }

    return mypoint;
}

关于c++ - 如何在 C++ 中返回结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59079676/

相关文章:

c++ - 使用 malloc 分配比现有内存更多的内存

c++ - Thrift 与 Protocol Buffer

c++ - 使用 std::string 作为字符数组

c - 将用户输入的大数字存储到整数数组中

C++:无法从相同类型的常量初始化枚举值

java - 使用java删除另一个数组中的数组

c - 声明数组但不物理分配它

javascript - 传递带有嵌套函数的函数和带有 array.map 的当前值

c++ - 使用 C++ 中的自定义元素进行 Const 结构初始化

C++ 方法声明不兼容