PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.c > sizeof and passing pointer
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
sizeof and passing pointer

Réponse
 
LinkBack Outils de la discussion
Vieux 21/10/2007, 18h13   #1
jason
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut sizeof and passing pointer

Hello,

I'm a beginning C programmer and I have a question regarding arrays and
finding the number of entries present within an array.

If I pass an array of structures to a function, then suddenly I can't use
sizeof(array) / sizeof(array[0]) anymore within that function ?

- What point am I missing ?

To show an example below. The commented out code that works where as the
exact same code, only wrapped in a function does not work ?

Thank you...

#include <stdio.h>

typedef struct {
char *name;
char *cat;
char *desc;
int wday;
int dur;
} entry_t;

entry_t entries[] = {
{ "dummy", "todo", "explanation", 1, 20 },
{ "not", "bla", "foobar", 1, 10 },
{ "check", "nowhere", "for something", 1, 20 }
};

void task_dump(entry_t *);

int main(int argc, char *argv[]) {
/*
int i = 0;
int max = 0;

max = sizeof(entries) / sizeof(entries[0]);
for(i = 0; i < max; i++) {
printf(" -- %02d\n", i);
printf(" name : %s\n", entries[i].name);
printf(" catagory : %s\n", entries[i].cat);
printf(" descript : %s\n", entries[i].desc);
printf(" weekday : %d\n", entries[i].wday);
printf(" duration : %d\n", entries[i].dur);
}
*/

task_dump(entries);

return 0;
}

void task_dump(entry_t *data) {
int i = 0;
int max = 0;

/* this doesn't work ? */
max = sizeof(data) / sizeof(data[0]);
for(i = 0; i < max; i++) {
printf(" -- %02d\n", i);
printf(" name : %s\n", data[i].name);
printf(" catagory : %s\n", data[i].cat);
printf(" descript : %s\n", data[i].desc);
printf(" weekday : %d\n", data[i].wday);
printf(" duration : %d\n", data[i].dur);
}

return;
}
  Réponse avec citation
Vieux 21/10/2007, 18h36   #2
Malcolm McLean
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer


"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().

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

  Réponse avec citation
Vieux 21/10/2007, 18h42   #3
Gordon Burditt
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer

>I'm a beginning C programmer and I have a question regarding arrays and
>finding the number of entries present within an array.
>
>If I pass an array of structures to a function, then suddenly I can't use
>sizeof(array) / sizeof(array[0]) anymore within that function ?


You can pass a *pointer* to an array of structures to a function.
It may look like you're passing the array, and the syntax makes it
easy to be fooled, but you're not. The size of the array you passed
isn't passed with the pointer to the array, so if you want the size,
you have to do it manually (e.g. pass it as another argument to the
function).

> - What point am I missing ?


sizeof applied to a pointer does not give the size of what it points
at, except occasionally by accident. It gives the size of the pointer.


  Réponse avec citation
Vieux 21/10/2007, 18h42   #4
jason
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer

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 ?

Thank you.

Jason.

  Réponse avec citation
Vieux 21/10/2007, 19h12   #5
Malcolm McLean
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer


"jason" <jisis@notmal.com> wrote in message news:471b8fa0$0$14414
> 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 ?
>


int main(void)
{
int array[10] = {1,2,3,4,5,6,7,8,910};

printf("array is %d bytes\n", (int) sizeof(array));
foo(array, 10);
}

void foo(int *ptr, int N)
{
int i;

printf("pointer is %d\n", (int) sizeof(ptr))'
/* treat as array */
for(i=0;i<N;i++)
print("%d\n", ptr[i]);
/* treat as pointer */
for(i=0;i<N;i++)
printf("%d\n", *ptr++);
}

in main your array is an array. When you pass it to foo it converts -
decays - into a pointer. arrays are very nearly, but not quite, constant
pointers. You can use the brackets notation on either an array or a pointer.
However you can also increment a pointer. Whilst sizeof(ptr) gives the size
of the memory item needed to hold the address, usually 4 bytes, whilst
sizeof(array) gives the size of the data in the array, probably either 20 or
40 bytes.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

  Réponse avec citation
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
Vieux 21/10/2007, 19h48   #7
Keith Thompson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer

jason <jisis@notmal.com> writes:
[...]
> 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 ?


It's really not about argument passing.

An expression of array type is implicitly converted to a pointer to
the first element of the array *unless* it's the operand of a unary
"&" or "sizeof" operator, or it's a string literal used in an
initializer for an array.

All this and more is explained in section 6 of the comp.lang.c FAQ,
<http://www.c-faq.com>.

--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
  Réponse avec citation
Vieux 21/10/2007, 19h49   #8
jason
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer [solved]


People,

Thank you so much for all the great explanations. I now understand now
the actual problem. [In such that's not really a problem :-)]

Thankx..

Jason




On Sun, 21 Oct 2007 19:12:25 +0100, Malcolm McLean wrote:
> "jason" <jisis@notmal.com> wrote in message news:471b8fa0$0$14414
>> 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 ?
>>
>>

> int main(void)
> {
> int array[10] = {1,2,3,4,5,6,7,8,910};
>
> printf("array is %d bytes\n", (int) sizeof(array)); foo(array, 10);
> }
>
> void foo(int *ptr, int N)
> {
> int i;
>
> printf("pointer is %d\n", (int) sizeof(ptr))' /* treat as array */
> for(i=0;i<N;i++)
> print("%d\n", ptr[i]);
> /* treat as pointer */
> for(i=0;i<N;i++)
> printf("%d\n", *ptr++);
> }
>
> in main your array is an array. When you pass it to foo it converts -
> decays - into a pointer. arrays are very nearly, but not quite, constant
> pointers. You can use the brackets notation on either an array or a
> pointer. However you can also increment a pointer. Whilst sizeof(ptr)
> gives the size of the memory item needed to hold the address, usually 4
> bytes, whilst sizeof(array) gives the size of the data in the array,
> probably either 20 or 40 bytes.


  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 06h11.


Édité par : vBulletin® version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 0,14469 seconds with 16 queries