Passing addresses into functions

I'm writing in c btw.

I have the address of a memory block, float ptr, containing N floating point numbers.

I would like to pass this address into a custom function, so I can read the floating point numbers in the block.

How would I declare the arguments for such a function?

I know normally I can acquire the value of the 2nd number in the block by doing *(ptr + 1) (in the main()).

Would I have to do something like void function(float ptr), and when calling the function do function(&ptr), then in the function do *(*ptr+1) to refer to the 2nd number in the block )?

It's a little like a pointer to a pointer situation.
Last edited on
usually u would do

1
2
3
4
5
void function(float *ptr)
{
      //Access The Second Element
      *(ptr+1);
}

and call this function via
function(&ptr[0]);

or if u declared ptr as float *ptr;:
function(ptr);
Last edited on
For your function, you would generally do something like this:

1
2
3
void function(float* ptr /*the array*/, unsigned int size) {
   //...
}


To pass it, you already have a float* ptr (I'm assuming you just made a typo there), so you just pass it directly to the function (with the size).
Good help guys, but Incubbus, wouldn't *(ptr+1) give me the address where the ptr is located plus one sizeof(float) block.

Rather than the address ptr is holding, the address of the first float in the memory block, plus sizeof(float), giving us the what is contained in the 2nd float sized block (the 2nd float).
The following syntaxes are functionally equivalent:

1
2
*(ptr + 1 )
ptr[ 1 ]

@ john: nah.. the function prototype expects to be handed over a pointer ( that´s why we declare the arguments as float* ptr and not float ptr - which would be a floating point number instead of a pointer to an floating point number.

because u said
I have the address of a memory block, float ptr, containing N floating point numbers.
, ur float ptr would be an array : float ptr[N] or an float *ptr = new float[n] where in both cases "ptr" itself would we a pointer pointing to the first adress of the memory blocks.

and because we have a pointr and the function expects a pointer we can hand over the pointer by just passing it to the function without the dereference or reference-operator!

of course, you could also pass an adress to the function by calling function(&ptr[N]) where we would pass the address of the n-th block to the function.


i hope this helps a bit and wasn´t too complicated :/
Topic archived. No new replies allowed.