Reputation: 3922
im writting program in ANSI C, and and have one function, where im passing pointer to semaphores array struct sembuf semb[5]
.
Now header of that function looks like:
void setOperations(struct sembuf * op[5], int nr, int oper)
But im getting warning:
safe.c:20: note: expected ‘struct sembuf **’ but argument is of type ‘struct sembuf (*)[5]’
How to solve that problem?
Edit
Calling:
setOperations(&semb, prawa, -1);
Upvotes: 1
Views: 1881
Reputation: 49403
You maybe over complicating this...
If you want to pass an array of structures, it's really no different than passing any array of anythings. Once you have the array, getting the address is simple, let me give you a quick example:
Let's say you have this struct:
typedef struct s {
int a;
int b;
} mys;
If you want to declare it statically in your main()
you can do:
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
Now we can have our function that accepts the array and changes the values:
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;
}
}
Once that returns we can print the values from main()
with some other loop like:
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);
And we'll get some output that looks like:
>> ./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
So you can see it's the same array (same address) and that's how you get the array of structs to the other function. Did that clear it up?
Upvotes: 0
Reputation: 64308
This is how the function should be declared if you want to pass a pointer to an array and not an array of pointers:
void setOperations(struct sembuf (*op)[5], int nr, int oper);
Upvotes: 6
Reputation: 11794
Your current declaration (struct sembuf * op[5]
) means an array of 5 pointers to struct sembuf
.
Arrays are passed as pointer anyway, so in the header you need: struct sembuf op[5]
.
A pointer to the array will be passed anyway. No array will be copied.
Alternative way of declaring this argument would be struct sembuf *op
, which is a pointer to struct sembuf
.
Upvotes: 3