[英]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.所以对于array[2]
,我还想说array[2].num = 2
我希望每个站点都有一个从 0 到 N-1 的唯一站点编号num
。 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. Output array[i].num
的不同 i 值给出 0、1、32767。然而,为了增加 i,我希望看到从 0 到 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.我对结构非常陌生,所以如果你能解释我在哪里犯了错误,我将非常感谢你作为一个 noice 程序员的帮助。
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.如果我正确理解您的问题,我认为您的问题来自您的fillStruct()
function。 The loop in this function will only execute once, instead of N times.这个 function 中的循环只会执行一次,而不是 N 次。 You never exceed k=0, so you set the num
member for array[0]
and then return array[0]
.您永远不会超过 k=0,因此您为array[0]
设置num
成员,然后返回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.当您返回主 function 时,您可以准确地打印array[0]
的位置,但数组中的后续站点编号只是随机的未初始化值。
Instead, you want the return statement to be outside of the loop block, so the function should like like...相反,您希望 return 语句位于循环块之外,因此 function 应该像...
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).现在,当您返回主 function 时,您将有 20 个站点,编号为 0 到 19(N=20)。
Also note that in the code you gave, you are not using the return value of fillStruct()
.另请注意,在您提供的代码中,您没有使用fillStruct()
的返回值。
Hope that helps, let me know if I missed something.希望对您有所帮助,如果我错过了什么,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.