struct args中的函数指针?

时间:2014-07-10 03:31:03

标签: c struct function-pointers

foo是一个struct,包含5个标量变量(ABCDF)和一个数组(E)。令我困惑的是f[0]f[1]f[2]在此背景下的内容以及此处发生的事情。

int     
bar(struct foo *f)
{
    f[1].C = f[0].B > f[2].C;
    f[0].E[-1] = f[0].D;
    f[0].A = f[1].C;
}

f[0]f[1]f[2]个别结构是否包含成员变量?有人可以解释一下吗?感谢。

4 个答案:

答案 0 :(得分:2)

  

f[0]f[1]f[2]个别结构是否包含成员变量?

是。 f是指向struct foo个实例数组的指针f[0]是该数组的第一个此类成员,f[1]是第二个成员,等等。您可以这样称呼它:

struct foo fArray[3];
// ... Initialize fArray[0], fArray[1], fArray[2] etc. ...
bar(fArray);

答案 1 :(得分:2)

您正在做的是,您将一个引用(指针)传递给struct foo数组到函数bar

您必须拥有与以下内容类似的代码:

struct foo  myFoos[10]; // an array with 10 elements of struct foo
struct foo *mallocedFoos;
// here goes some code to initialize the elements of the array
bar(&myFoos[0]);          // pass a reference to (address of/pointer to) the array

// or something like this is happening
mallocedFoos = malloc(sizeof(struct foo) * 10);
// here goes some code to initialize allocated memory
bar(mallocedFoos);        // pass the 'struct foo *' to the function

要更好地理解这个概念,请参阅this示例。

答案 2 :(得分:2)

是的,在此上下文中,f[0]f[1]等是struct foo类型数组的元素。

对我来说更有趣的是这一行:

f[0].E[-1] = f[0].D;

我没有意识到负面索引被允许,但是this question解释说数组索引只是指针数学,所以它是一种模糊的说法:

f[0].D = f[0].D;

据我所知,这基本上没用。

同样有趣:

f[0].C = f[0].B > f[2].C;

这会将f[0].C设置为布尔值,通常不会与>运算符进行比较,因此不同的C成员可能会使用不同的函数。

考虑到这个功能的奇特性,我觉得你的困惑是有道理的。

答案 3 :(得分:1)

在这种情况下,farray of structures
相似 struct node = { int A; //A to D and F are scalar variables int B; int C; int D; int E[10]; //E is an array of integers int F; } struct node f[10]; //f is an array of structs

有关详细信息,您还可以参考How do you make an array of structs in C?