Reputation: 16780
void test()
{
int buf[1000];
//populate buf
foo(buf);//is this correct? Can we pass buf as a pointer that foo expects?
}
void foo(void*ptr)
{}
EDIT: if foo were fwrite, would the above(mechanism of passing buf so as to supply fwrite with content to write into some file) still be applicable?
Upvotes: 1
Views: 12519
Reputation: 108968
As the other answers pointed out, yes, you can pass buf
to the function.
However, inside the function, the variable ptr
has type void*
. And there's only a few things you can do with ptr
itself. Usually you convert it (with or without a cast) to something relevant, like int*
.
void foo(void *ptr) {
int *iptr;
iptr = ptr;
/* now use iptr */
}
Upvotes: 1
Reputation: 43235
Yes its correct. You can use the "ptr" pointer in your foo function. http://codepad.org/HwYd0GAh
Upvotes: 1
Reputation: 34615
Its perfectly valid in C. foo
argument is a pointer that can point to any type. When you pass an array, it decays to a pointer pointing to the first element of the array (i.e.,address location of the first element is passed). So,
ptr -> &buf[0] ;
Upvotes: 2