Karthik Kumar said:
(e-mail address removed) wrote:
Hi, is it possible to find the dimension of an array using a pointer?
main()
{
int a[10];
f(a);
return;
}
f(int *b)
{
/*how can I know here the size of b??*/
/*because sizeof(b) is always 4*/
/*and sizeof(b[0]) is always 4*/
Both ought to be the same, since both are pointers.
And you are trying to get the size of a pointer variable
(which is implementation - dependent).
As Artie had already suggested, pass the length
explicitly as an argument to the function.
I know, but I can't do it.
Why not?
Do you thing it is possible to find in the stack this information?
No. Seriously, there is no (portable) way to find out the physical
size of an array based on a pointer to the first element alone. You
have two choices:
1. Save the size of the array and either pass it as an argument
or save it in a file scope variable.
2. Write a special sentinel value to the last element of the
array,
like how C strings are arrays of char terminated with a 0.
This
method is far more error prone, though, and won't necessarily
tell
you the *physical* size of the array, just how many elements
come
before the sentinel.
Actually, there's a third choice: pass a pointer to the array (which
is not the same thing as passing a pointer to the first element):
int f(int (*b)[10])
{
/* sizeof *b == sizeof (int) * 10 */
}
int main (void)
{
int a[10];
f(&a);
return 0;
}
The only problem is that this assumes you're only working with arrays
with 10 elements, so it's not very flexible.
I mean, I have the position of the first element of the array, then,
moving up and down in the stack, I find this number. Or is the stack a
simple storage for the program and only it knows this information.
Aside from the fact that not all machines even *use* a stack for
passing arguments to functions, what you're passing is a *pointer*
type, not an array type. As far as the called function is concerned,
b is a pointer to a single int object, not an array. That object may
be the first element of an array. It may be the last element of an
array. It may be a scalar variable. There is simply no way for the
called function to know based on the pointer alone.
And then how does really operate sizeof? Has it an internal table with
all variables?
Possibly. Or it could do something completely different. It's up to
the compiler writer to decide how sizeof actually gets implemented.
Thank you
Best Regards
Dati Remo