Afficher un message
Vieux 21/10/2007, 19h40   #6
Ben Bacarisse
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer

jason <jisis@notmal.com> writes:

> On Sun, 21 Oct 2007 18:36:09 +0100, Malcolm McLean wrote:
>
>> "jason" <jisis@notmal.com> wrote in message
>>> Hello,
>>>
>>> I'm a beginning C programmer and I have a question regarding arrays and
>>> finding the number of entries present within an array.
>>>

>> Arrays decay to pointers when you pass them to functions. So you need to
>> pass in the number of elements as a separate parameter.
>>
>> When you start writing real programs you will find that the number of
>> cases where you know an array's size at compile time is quite few.
>> Usually the size is determined by the data the user inputs, so you must
>> allocate the space with malloc().

>
> Ok thankx for that !
>
> But just to make sure; what does `decay' exactly mean in this case ? And
> what properties of the pointer, when passed to a function actually
> change ?


What is going on comes from this wording the C standard:

Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object

so, in fact, almost every use of an array involves this conversion.
Writing the name of an array in a function call is only one example of
the general rule.

Your example of determining the number of elements:

sizeof table / sizeof *table

involves one of each. 'table' is not converted in the numerator
(because it is the operand of sizeof) but it is in the denominator.

--
Ben.
  Réponse avec citation
 
Page generated in 0,09694 seconds with 9 queries