使用结构数组作为函数参数 [英] Using an array of structure as a function argumant

查看:59
本文介绍了使用结构数组作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数中使用结构数组.有人可以帮我提供示例吗?
我编写了如下代码:

I want to use an array of structure in a function.Could anybody help me with a sample?
I have written the code as below:



...


...

struct Chrom             // creating the chrom structure
   {
      int Num_Chrom;
      unsigned int Gen[Chrom_Size];
      int Fit;
   };                   // now we have a chrom type that we can use

void Initial_Pop(Chrom[], int);


...


...

void Initial_Pop(Chrom PopInitial[], int Pop_Size){
int i=0,j=0;
unsigned int Random;
unsigned int temp1[Num_VehicleKind-1];
unsigned int temp2[Num_Depot-1];
    for(j=0;j<Pop_Size;j++){                      // loop of j to choose chromes from [0] to [pop_size]
        for(i=0;i<(Num_VehicleKind-1);i++){       // loop of i to generate (Num_VehicleKind-1) random integer
            temp1[i]=1+rand()%Num_Depot;      // make the random integer value between 1 and (Num_Depot)

        }//end of for(i)

        for(i=0;i<(Num_Depot-1);i++){            // loop of i to generate (Num_Depot-1) random integer
            temp2[i]=1+rand()%Num_VehicleKind;   // make the random integer value between 1 and (Num_VehicleKind)
            }//end of for(i)

        int k1=(Num_VehicleKind-1);
        int k2=(Num_Depot-1);
        int p=(Num_VehicleKind+Num_Depot-2);
        while(k1==-1 || k2==-1){           // loop of i to generate (Num_Depot-1) random integer
            //Random=rand();                       // creating random value
            Random=(rand()%2);
            if (Random==0){                                    // make the random integer value between 1 and (Num_VehicleKind)
                PopInitial[j].Gen[p]=temp1[k1];
                k1--;
                p--;
            }//end of if
            else{
                PopInitial[j].Gen[p]=temp2[k2];
                k2--;
                p--;
            }//end of else
            }//end of while



当我逐步运行该程序时,它中断在行



when I run the program step by step, it broke in line

PopInitial[j].Gen[p]=temp1[k1];

推荐答案

while(k1==-1 || k2==-1){           // loop of i to generate (Num_Depot-1)


然后,您可以将这些值用作某个数组的索引.数组的索引从0到(正)N;任何负索引都将尝试寻址不属于该数组的内存,因此会引起问题.


You then use these values as indices into some array. Arrays are indexed from 0 to (positive)N; any negative index will try to address memory that does not belong to the array and will therefore cause problems.


这篇关于使用结构数组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆