简体   繁体   中英

Why doesn't my function work using structures in C?

I am creating an array that contains the locations of sites in space. So for array[2] , I also want to say array[2].num = 2 I want each site to have a unique site number num from 0 to N-1. Output different values of i for array[i].num gives 0, 1, 32767. Whereas, for increasing i, I want to see incrementing values from 0 to N-1.

I am very new to structures so if you could explain where I am making my mistakes I would much appreciate your help as a noice programmer.

 typedef struct site_t
{
    int num; // want to add more varaibels later hence type struct //
} site;
site fillStruct( site[], int);
int main()
{   int i;
    const int N = 20;
    site array[N];
    fillStruct(array, N);
    for (i = 0; i < N; i++) {
    printf("location of site %d\n", array[i].num);
}
}

site fillStruct(site array[], int size) {
    for (int k = 0; k < size; k++) {;
        array[k].num = k;   
        return array[k];
        } 

}

If I'm understanding your question correctly, I think your problem comes from your fillStruct() function. The loop in this function will only execute once, instead of N times. You never exceed k=0, so you set the num member for array[0] and then return array[0] .

When you return to your main function, you print the location for array[0] accurately, but subsequent site numbers in the array are just random uninitialized values.

Instead, you want the return statement to be outside of the loop block, so the function should like like...

site fillStruct(site array[], int size) {
    int k; 

    for (k = 0; k < size; k++) {;
        array[k].num = k;
    }

    return array[k-1]; // Returns the last site in the array
}

Now, when you return to your main function you will have 20 sites numbered 0 to 19 (for N=20).

Also note that in the code you gave, you are not using the return value of fillStruct() .

Hope that helps, let me know if I missed something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM