无法在循环中击中数组/变量的价值

cannot give value to struck array/variable in a loop

本文关键字:变量 循环 数组      更新时间:2023-10-16

我正在尝试将坐标给多边形。arrayxarrayy是包含我的X和Y坐标的数组。问题是,我无法将数组的值提供给polygon点结构。

#include <iostream>
#include <fstream>
#include <string>
struct Point
{
    int x,y;
};
int main()
{    
  Point polygon[]={};
  int n=0, arrayx[1024] = {0} , arrayy[1024] = {0};
   //input
   ifstream iFile;
   iFile.open("in.txt");
        while(iFile >> arrayx[n] >> arrayy[n])
        {
            n = n + 1;
        }
    iFile.close(); 
    int k=n;          
    for (int j=0; j<= k; j++)
    {
        polygon[j] = (Point){arrayx[j],arrayy[j]}; //something wrong here
        //output
        ofstream myfile;
        myfile.open ("out3.txt", ios::app);
        myfile  <<"k = " <<k << "----" <<j << ") polygon.x = "<< polygon[j].x  <<" arrayx = "<<arrayx[j] << " polygon[j].y = "<< polygon[j].y  <<" arrayy = "<<arrayy[j] << "n";
        myfile.close();
    }
}

我还尝试了以下更改代码:

polygon[j].x = arrayx[j];
polygon[j].y = arrayy[j];

输入:

260 673
565 735
780 619
746 408
333 400

输出:

k = 260 
j = 673    
polygon[j].x = 7209071     
arrayx = 0 
polygon[j].y = 7471220 
arrayy = 0

突然 k将其值更改为260。循环j变量转到673,(不j = 0,1,2,3,4,5仅一次倾斜和断裂),即使arrays[673]是空的,polygon也获得了一些数字。

我对C 没有太多经验,我很难单独解决它。

您将无法分配任何内容,因为数组为空

Point polygon[]={};

这应该引起编译器错误,因为在标准C 中不允许使用0个大小的数组。