Namratha
Namratha

Reputation: 16780

convert int array to pointer in C

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

Answers (5)

pmg
pmg

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

DhruvPathak
DhruvPathak

Reputation: 43235

Yes its correct. You can use the "ptr" pointer in your foo function. http://codepad.org/HwYd0GAh

Upvotes: 1

Mahesh
Mahesh

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

MByD
MByD

Reputation: 137282

Yes, You will always pass buf to function as a pointer.

Upvotes: 1

user623879
user623879

Reputation: 4142

Yes you can do that.

buf is the base pointer of the array.

Upvotes: 1

Related Questions