1

我用 ANSI C 编写程序,并且有一个函数,其中我将指针传递给信号量数组struct sembuf semb[5]

现在该函数的标题如下所示:

void setOperations(struct sembuf * op[5], int nr, int oper)

但我收到警告:

safe.c:20: note: expected ‘struct sembuf **’ but argument is of type ‘struct sembuf (*)[5]’

如何解决这个问题?

编辑
调用:

setOperations(&semb, prawa, -1);
4

3 回答 3

6

如果要将指针传递给数组而不是指针数组,这就是函数的声明方式:

void setOperations(struct sembuf (*op)[5], int nr, int oper);
于 2012-11-14T12:58:01.977 回答
3

您当前的声明 ( struct sembuf * op[5]) 表示一个由 5 个指针组成的数组struct sembuf

数组无论如何都是作为指针传递的,所以在你需要的标题中:struct sembuf op[5]. 无论如何都会传递指向数组的指针。不会复制任何数组。声明此参数的另一种方法是struct sembuf *op,它是指向 的指针struct sembuf

于 2012-11-14T12:52:27.997 回答
0

你可能过于复杂了......

如果你想传递一个结构数组,它实际上与传递任何数组没有什么不同。一旦你有了数组,获取地址就很简单了,让我给你一个简单的例子:

假设你有这个结构:

typedef struct s {
    int a;
    int b;
} mys;

如果你想在你的中静态声明它,main()你可以这样做:

int main(int argc, char *argv[])
{
    mys local[3];
    memset(local, 0, sizeof(mys)*3);   // Now we have an array of structs, values are 
                                       // initialized to zero.

    // as a sanity check let's print the address of our array:
    printf("my array is at address: %#x\n", local);

    changeit(local, 3);  // now we'll pass the array to our function to change it

现在我们可以让我们的函数接受数组并更改值:

void changeit(mys remote[], int size)
{
    int count;
    printf("my remote array is at address: %#x\n", remote); //sanity check
    for(count = 0; count < size; count++) {
        remote[count].a = count;
        remote[count].b = count + size;
    }
}

一旦返回,我们可以main()使用其他循环打印值,例如:

for(int count = 0; count < 3; count ++)
    printf("struct[%d].a = %d\n struct[%d].b = %d\n", 
           count, local[count].a, count, local[count].b);

我们将得到一些如下所示的输出:

>> ./a.out
   my array is at address: 0xbf913ac4
   my remote array is at address: 0xbf913ac4
   struct[0].a = 0
   struct[0].b = 3
   struct[1].a = 1
   struct[1].b = 4
   struct[2].a = 2
   struct[2].b = 5

所以你可以看到它是同一个数组(相同的地址),这就是你如何将结构数组传递给另一个函数。这清楚了吗?

于 2012-11-14T13:43:40.480 回答