Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #63160 > unrolled thread

sizeof(arr[0])

Started bykuznecov.alexey@gmail.com
First post2015-06-10 12:38 -0700
Last post2015-06-18 20:38 +0000
Articles 20 on this page of 96 — 21 participants

Back to article view | Back to comp.lang.c


Contents

  sizeof(arr[0]) kuznecov.alexey@gmail.com - 2015-06-10 12:38 -0700
    Re: sizeof(arr[0]) James Kuyper <jameskuyper@verizon.net> - 2015-06-10 16:00 -0400
      Re: sizeof(arr[0]) kuznecov.alexey@gmail.com - 2015-06-10 14:53 -0700
    Re: sizeof(arr[0]) kuznecov.alexey@gmail.com - 2015-06-10 13:11 -0700
    Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-10 21:21 +0100
      Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-10 22:08 +0100
        Re: sizeof(arr[0]) Andrew Cooper <amc96@cam.ac.uk> - 2015-06-11 00:27 +0100
          Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-11 00:34 +0100
            Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-11 00:38 +0100
            Re: writing code for people who don't know the language (was: sizeof(arr[0])) Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-06-10 21:16 -0400
            Re: writing code for people who don't know the language Richard Heathfield <rjh@cpax.org.uk> - 2015-06-11 02:35 +0100
              Re: writing code for people who don't know the language Bartc <bc@freeuk.com> - 2015-06-11 11:16 +0100
            Re: writing code for people who don't know the language Bartc <bc@freeuk.com> - 2015-06-11 11:29 +0100
              Re: writing code for people who don't know the language gazelle@shell.xmission.com (Kenny McCormack) - 2015-06-11 11:43 +0000
            Re: sizeof(arr[0]) Paul N <gw7rib@aol.com> - 2015-06-14 13:13 -0700
              Re: sizeof(arr[0]) Philip Lantz <prl@canterey.us> - 2015-06-14 17:52 -0700
            Re: sizeof(arr[0]) "Bill Cunningham" <nospam@nspam.invalid> - 2015-06-15 14:26 -0400
              Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-15 19:34 +0100
                Re: sizeof(arr[0]) "Bill Cunningham" <nospam@nspam.invalid> - 2015-06-15 14:55 -0400
                  Re: sizeof(arr[0]) Melzzzzz <melz@zzzzz.com> - 2015-06-15 20:59 +0200
                  Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-15 20:11 +0100
                    Re: sizeof(arr[0]) "Bill Cunningham" <nospam@nspam.invalid> - 2015-06-15 15:22 -0400
                      Re: sizeof(arr[0]) David Kleinecke <dkleinecke@gmail.com> - 2015-06-16 09:51 -0700
                        Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 10:51 -0700
                          Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-16 19:14 +0100
                            Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 11:43 -0700
                              Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-16 20:03 +0100
                          Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-16 19:15 +0100
                            Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 11:34 -0700
                              Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-16 20:28 +0100
                                Re: sizeof(arr[0]) James Kuyper <jameskuyper@verizon.net> - 2015-06-16 15:42 -0400
                                  Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-16 13:35 -0700
                                    Re: sizeof(arr[0]) James Kuyper <jameskuyper@verizon.net> - 2015-06-16 16:59 -0400
                                    Re: sizeof(arr[0]) Dr Nick <nospam-4@temporary-address.org.uk> - 2015-06-16 22:05 +0100
                                      Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-16 14:27 -0700
                                        Re: sizeof(arr[0]) Dr Nick <nospam-4@temporary-address.org.uk> - 2015-06-17 07:07 +0100
                                  Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-17 01:22 +0100
                                Re: sizeof(arr[0]) glen herrmannsfeldt <gah@ugcs.caltech.edu> - 2015-06-16 19:45 +0000
                                Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 13:03 -0700
                                  Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-17 10:58 +0100
                                    Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 05:58 -0700
                                      Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-17 15:46 +0100
                                        Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 08:14 -0700
                                          Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-17 17:58 +0100
                                            Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 10:07 -0700
                                              Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 10:09 -0700
                                                Re: sizeof(arr[0]) David Kleinecke <dkleinecke@gmail.com> - 2015-06-17 10:46 -0700
                                              Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-17 11:13 -0700
                                                Re: sizeof(arr[0]) Nathan Wagner <nw@hydaspes.if.org> - 2015-06-18 07:14 +0000
                                                  Re: sizeof(arr[0]) David Brown <david.brown@hesbynett.no> - 2015-06-18 09:54 +0200
                                                  Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-18 05:19 -0700
                                          Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-17 10:53 -0700
                                            Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 11:17 -0700
                                              Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 13:59 -0700
                                                Re: sizeof(arr[0]) Ian Collins <ian-news@hotmail.com> - 2015-06-18 13:41 +1200
                                            Re: sizeof(arr[0]) David Brown <david.brown@hesbynett.no> - 2015-06-18 10:04 +0200
                              Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-16 13:18 -0700
                                Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-16 21:30 +0100
                                  Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 13:53 -0700
                                Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 13:43 -0700
                                  Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-16 21:52 +0100
                                    Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 14:01 -0700
                                    Re: sizeof(arr[0]) David Brown <david.brown@hesbynett.no> - 2015-06-16 23:49 +0200
                                      Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 14:58 -0700
                                        Re: sizeof(arr[0]) David Brown <david.brown@hesbynett.no> - 2015-06-17 14:10 +0200
                                          Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-17 13:20 +0100
                                  Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-16 14:16 -0700
                                    Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 14:39 -0700
                          Re: sizeof(arr[0]) gazelle@shell.xmission.com (Kenny McCormack) - 2015-06-16 18:38 +0000
                            Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-16 11:45 -0700
                              Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-16 13:22 -0700
                                Re: sizeof(arr[0]) gazelle@shell.xmission.com (Kenny McCormack) - 2015-06-16 21:25 +0000
                        Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-16 11:05 -0700
                          Re: sizeof(arr[0]) James Kuyper <jameskuyper@verizon.net> - 2015-06-16 14:15 -0400
                          Re: sizeof(arr[0]) David Kleinecke <dkleinecke@gmail.com> - 2015-06-17 10:07 -0700
                            Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-17 11:16 -0700
                              Re: sizeof(arr[0]) David Kleinecke <dkleinecke@gmail.com> - 2015-06-18 10:22 -0700
                                Re: sizeof(arr[0]) Keith Thompson <kst-u@mib.org> - 2015-06-18 10:42 -0700
                                  Re: sizeof(arr[0]) David Kleinecke <dkleinecke@gmail.com> - 2015-06-18 11:41 -0700
                    Re: sizeof(arr[0]) Philip Lantz <prl@canterey.us> - 2015-06-16 00:12 -0700
                      Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-16 10:12 +0100
                        Re: sizeof(arr[0]) Philip Lantz <prl@canterey.us> - 2015-06-16 09:12 -0700
                          Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-16 17:32 +0100
      Re: sizeof(arr[0]) kuznecov.alexey@gmail.com - 2015-06-10 14:56 -0700
        Re: sizeof(arr[0]) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-06-10 23:53 +0100
        Re: sizeof(arr[0]) Bartc <bc@freeuk.com> - 2015-06-11 00:33 +0100
          Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-11 00:37 +0100
    Re: sizeof(arr[0]) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 06:05 -0700
      [OT] The number 42 (was Re: sizeof(arr[0])) David Brown <david.brown@hesbynett.no> - 2015-06-17 16:07 +0200
        Re: [OT] The number 42 (was Re: sizeof(arr[0])) "Rick C. Hodgin" <rick.c.hodgin@gmail.com> - 2015-06-17 08:23 -0700
          Re: [OT] The number 42 (was Re: sizeof(arr[0])) David Brown <david.brown@hesbynett.no> - 2015-06-18 10:21 +0200
        Re: [OT] The number 42 (was Re: sizeof(arr[0])) David Kleinecke <dkleinecke@gmail.com> - 2015-06-17 10:35 -0700
          Re: [OT] The number 42 (was Re: sizeof(arr[0])) David Brown <david.brown@hesbynett.no> - 2015-06-18 10:18 +0200
            Re: [OT] The number 42 (was Re: sizeof(arr[0])) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-18 10:08 +0100
      Re: sizeof(arr[0]) Richard Heathfield <rjh@cpax.org.uk> - 2015-06-17 15:13 +0100
        Re: sizeof(arr[0]) raltbos@xs4all.nl (Richard Bos) - 2015-06-18 20:38 +0000

Page 1 of 5  [1] 2 3 4 5  Next page →


#63160 — sizeof(arr[0])

Fromkuznecov.alexey@gmail.com
Date2015-06-10 12:38 -0700
Subjectsizeof(arr[0])
Message-ID<5c0c353e-3650-4ab7-a956-0ddfc39b0507@googlegroups.com>
There is a well know pattern of figuring out array length:
  int arr[10];
  size_t len = sizeof(arr) / sizeof(arr[0]);
  assert(len == 10);

This pattern applies to static arrays and auto arrays of constant size. It also applies to variable length arrays in C99.

I want to apply similar idea for figuring out dynamic array size in bytes:
  size_t known_len = 10;
  int *ptr = malloc(known_len);
  size_t size = known_len * sizeof(ptr[0]);
  assert(size == known_len * sizeof(int));

This is nicer than "known_len * sizeof(int)" because "sizeof(ptr[0])" doesn't refer to actual array element type. Hence it doesn't require reader of the code to know the type.

However it is unclear to me whether expression "sizeof(ptr[0])" can lead to undefined behavior. As it is expanded:
  sizeof(ptr[0]) -> sizeof(*((ptr) + (0))) -> sizeof(*ptr)
The result expression is questionable in case if ptr is 0:
  sizeof(*((int*) 0))

According to a C99 standard:
~~~
(C99, 6.3.2.3p3 ): "An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant."
Dereferencing a null pointer is undefined behavior.

(C99, 6.5.3.2.p4) "If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.87)"
and

87): "Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime."
~~~

But it's never specified whether sizeof of such expression can lead to undefined behavior. In fact such sizeof should be evaluated at compile time.

My questions are:
 - Can the expression "sizeof(ptr[0])" be used in the code when type of ptr is known and the value of ptr is not known?
 - Can such use be justified according to C99 standard? GNU GCC spec?

[toc] | [next] | [standalone]


#63161

FromJames Kuyper <jameskuyper@verizon.net>
Date2015-06-10 16:00 -0400
Message-ID<5578974E.6090706@verizon.net>
In reply to#63160
On 06/10/2015 03:38 PM, kuznecov.alexey@gmail.com wrote:
> There is a well know pattern of figuring out array length:
>   int arr[10];
>   size_t len = sizeof(arr) / sizeof(arr[0]);
>   assert(len == 10);
> 
> This pattern applies to static arrays and auto arrays of constant size. It also applies to variable length arrays in C99.
> 
> I want to apply similar idea for figuring out dynamic array size in bytes:
>   size_t known_len = 10;
>   int *ptr = malloc(known_len);

You've told malloc() to allocate 10 bytes of space.

>   size_t size = known_len * sizeof(ptr[0]);

You're calculating the size of 10 'int' objects. Unless sizeof ptr[0] ==
1, that's at least 10 bytes longer than the size of the object that was
allocated by your call to malloc().

>   assert(size == known_len * sizeof(int));
> 
> This is nicer than "known_len * sizeof(int)" because "sizeof(ptr[0])" doesn't refer to actual array element type. Hence it doesn't require reader of the code to know the type.
> 
> However it is unclear to me whether expression "sizeof(ptr[0])" can lead to undefined behavior. As it is expanded:
>   sizeof(ptr[0]) -> sizeof(*((ptr) + (0))) -> sizeof(*ptr)
> The result expression is questionable in case if ptr is 0:
>   sizeof(*((int*) 0))

ptr is a pointer object. It cannot have a value of 0, because 0 is an
arithmetic value, and ptr can only store pointer values. It can be a
null pointer, which could be result of writing

	ptr = 0;

but that works only because, in that context, '0' gets interpreted as a
null pointer constant, and then converted into a null pointer of the
same type as 'ptr', before being assigned to 'ptr'. That pointer might
or might not point at address 0. It might or might not be represented by
having all bits of 'ptr' set to 0. The only things guaranteed by the
standard is that after that assignment statement, ptr will compare equal
to all other null pointers (regardless of representation), and will
compare unequal to all non-null pointers.

> But it's never specified whether sizeof of such expression can lead to undefined behavior. In fact such sizeof should be evaluated at compile time.

One of the very most important things to know about the sizeof operator
is that "If the type of the operand is a variable length array
type, the operand is evaluated; otherwise, the operand is not evaluated
and the result is an integer constant." (6.5.3.4p2).
ptr[0] is an int, not a variable length array. It is therefore NOT
evaluated when the sizeof operator is applied to it.

> My questions are:
>  - Can the expression "sizeof(ptr[0])" be used in the code when type of ptr is known and the value of ptr is not known?

Yes, since the value is not used. Only the type of the expression matters.

>  - Can such use be justified according to C99 standard? GNU GCC spec?

Yes. C90 had similar wording, except that there was no exception for
variable length arrays, because those didn't exist in C90.

[toc] | [prev] | [next] | [standalone]


#63165

Fromkuznecov.alexey@gmail.com
Date2015-06-10 14:53 -0700
Message-ID<5afdac84-33a6-4c48-917f-65e232f7a3fe@googlegroups.com>
In reply to#63161
On Wednesday, June 10, 2015 at 1:00:23 PM UTC-7, James Kuyper wrote:
> On 06/10/2015 03:38 PM, kuznecov.alexey@gmail.com wrote:
> > There is a well know pattern of figuring out array length:
> >   int arr[10];
> >   size_t len = sizeof(arr) / sizeof(arr[0]);
> >   assert(len == 10);
> > 
> > This pattern applies to static arrays and auto arrays of constant size. It also applies to variable length arrays in C99.
> > 
> > I want to apply similar idea for figuring out dynamic array size in bytes:
> >   size_t known_len = 10;
> >   int *ptr = malloc(known_len);
> 
> You've told malloc() to allocate 10 bytes of space.
> 
> >   size_t size = known_len * sizeof(ptr[0]);
> 
> You're calculating the size of 10 'int' objects. Unless sizeof ptr[0] ==
> 1, that's at least 10 bytes longer than the size of the object that was
> allocated by your call to malloc().
> 
Correct. Sample code has an error.

> >   assert(size == known_len * sizeof(int));
> > 
> > This is nicer than "known_len * sizeof(int)" because "sizeof(ptr[0])" doesn't refer to actual array element type. Hence it doesn't require reader of the code to know the type.
> > 
> > However it is unclear to me whether expression "sizeof(ptr[0])" can lead to undefined behavior. As it is expanded:
> >   sizeof(ptr[0]) -> sizeof(*((ptr) + (0))) -> sizeof(*ptr)
> > The result expression is questionable in case if ptr is 0:
> >   sizeof(*((int*) 0))
> 
> ptr is a pointer object. It cannot have a value of 0, because 0 is an
> arithmetic value, and ptr can only store pointer values. It can be a
> null pointer, which could be result of writing
> 
> 	ptr = 0;
> 
> but that works only because, in that context, '0' gets interpreted as a
> null pointer constant, and then converted into a null pointer of the
> same type as 'ptr', before being assigned to 'ptr'. That pointer might
> or might not point at address 0. It might or might not be represented by
> having all bits of 'ptr' set to 0. The only things guaranteed by the
> standard is that after that assignment statement, ptr will compare equal
> to all other null pointers (regardless of representation), and will
> compare unequal to all non-null pointers.
> 
> > But it's never specified whether sizeof of such expression can lead to undefined behavior. In fact such sizeof should be evaluated at compile time.
> 
> One of the very most important things to know about the sizeof operator
> is that "If the type of the operand is a variable length array
> type, the operand is evaluated; otherwise, the operand is not evaluated
> and the result is an integer constant." (6.5.3.4p2).
> ptr[0] is an int, not a variable length array. It is therefore NOT
> evaluated when the sizeof operator is applied to it.
> 
> > My questions are:
> >  - Can the expression "sizeof(ptr[0])" be used in the code when type of ptr is known and the value of ptr is not known?
> 
> Yes, since the value is not used. Only the type of the expression matters.
> 
> >  - Can such use be justified according to C99 standard? GNU GCC spec?
> 
> Yes. C90 had similar wording, except that there was no exception for
> variable length arrays, because those didn't exist in C90.
Thanks! That's what I was looking for.

[toc] | [prev] | [next] | [standalone]


#63162

Fromkuznecov.alexey@gmail.com
Date2015-06-10 13:11 -0700
Message-ID<ab5bfe94-28a9-4d10-855c-04ee425d8afd@googlegroups.com>
In reply to#63160
On Wednesday, June 10, 2015 at 12:39:05 PM UTC-7, kuzneco...@gmail.com wrote:
> There is a well know pattern of figuring out array length:
>   int arr[10];
>   size_t len = sizeof(arr) / sizeof(arr[0]);
>   assert(len == 10);
> 
> This pattern applies to static arrays and auto arrays of constant size. It also applies to variable length arrays in C99.
> 
> I want to apply similar idea for figuring out dynamic array size in bytes:
>   size_t known_len = 10;
>   int *ptr = malloc(known_len);
>   size_t size = known_len * sizeof(ptr[0]);
>   assert(size == known_len * sizeof(int));
> 
My apologies for the typo. Of course malloc should be:
  int *ptr = malloc(known_len * sizeof(int));   

> This is nicer than "known_len * sizeof(int)" because "sizeof(ptr[0])" doesn't refer to actual array element type. Hence it doesn't require reader of the code to know the type.
> 
> However it is unclear to me whether expression "sizeof(ptr[0])" can lead to undefined behavior. As it is expanded:
>   sizeof(ptr[0]) -> sizeof(*((ptr) + (0))) -> sizeof(*ptr)
> The result expression is questionable in case if ptr is 0:
>   sizeof(*((int*) 0))
> 
> According to a C99 standard:
> ~~~
> (C99, 6.3.2.3p3 ): "An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant."
> Dereferencing a null pointer is undefined behavior.
> 
> (C99, 6.5.3.2.p4) "If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.87)"
> and
> 
> 87): "Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime."
> ~~~
> 
> But it's never specified whether sizeof of such expression can lead to undefined behavior. In fact such sizeof should be evaluated at compile time.
> 
> My questions are:
>  - Can the expression "sizeof(ptr[0])" be used in the code when type of ptr is known and the value of ptr is not known?
>  - Can such use be justified according to C99 standard? GNU GCC spec?

[toc] | [prev] | [next] | [standalone]


#63163

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2015-06-10 21:21 +0100
Message-ID<87381z8gbq.fsf@bsb.me.uk>
In reply to#63160
kuznecov.alexey@gmail.com writes:

> There is a well know pattern of figuring out array length:
>   int arr[10];
>   size_t len = sizeof(arr) / sizeof(arr[0]);
>   assert(len == 10);
>
> This pattern applies to static arrays and auto arrays of constant
> size. It also applies to variable length arrays in C99.
>
> I want to apply similar idea for figuring out dynamic array size in bytes:
>   size_t known_len = 10;
>   int *ptr = malloc(known_len);
>   size_t size = known_len * sizeof(ptr[0]);
>   assert(size == known_len * sizeof(int));

I don't know what this is supposed to do.  The main problem I see is
that the malloc call asks for less memory than you seem to need.  A
common idiom is

  int *ptr = malloc(known_len * sizeof *ptr);

Maybe you intended to write that, but then I don't know what all the
rest is about...  (And remember to check that the allocation succeeded!)

<snip>
> My questions are:
>  - Can the expression "sizeof(ptr[0])" be used in the code when type
>  of ptr is known and the value of ptr is not known?

Yes, the operand of sizeof is not evaluated in this case.

>  - Can such use be justified according to C99 standard? GNU GCC spec?

It's standard C99 and C11 (6.5.2.4 p2).

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#63164

FromRichard Heathfield <rjh@cpax.org.uk>
Date2015-06-10 22:08 +0100
Message-ID<mla8uu$8mj$1@dont-email.me>
In reply to#63163
On 10/06/15 21:21, Ben Bacarisse wrote:
> kuznecov.alexey@gmail.com writes:
>
<snip>
>> My questions are:
>>  - Can the expression "sizeof(ptr[0])" be used in the code when type
>>  of ptr is known and the value of ptr is not known?
>
> Yes, the operand of sizeof is not evaluated in this case.
>
>>  - Can such use be justified according to C99 standard? GNU GCC spec?
>
> It's standard C99 and C11 (6.5.2.4 p2).

It is also standard C90 and C95.

I would draw the OP's attention to the omission of parentheses from the 
operand of sizeof:

ptr = malloc(n * sizeof *ptr);

There is no more need to write sizeof(*ptr) than there is to write +(x).

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#63168

FromAndrew Cooper <amc96@cam.ac.uk>
Date2015-06-11 00:27 +0100
Message-ID<mlah50$e7a$1@flame.srcf.net>
In reply to#63164
On 10/06/2015 22:08, Richard Heathfield wrote:
> I would draw the OP's attention to the omission of parentheses from the
> operand of sizeof:
> 
> ptr = malloc(n * sizeof *ptr);
> 
> There is no more need to write sizeof(*ptr) than there is to write +(x).
> 

While true, it quickly gets deceptive for more complicated expressions
such as 'sizeof(*p)->foo', where sizeof evaluates to the size of foo,
rather than the size of the object pointed to by p.

You owe it to anyone who reads your code, not to add to the cognitive
load of attempting to interpret it.

~Andrew

[toc] | [prev] | [next] | [standalone]


#63170

FromRichard Heathfield <rjh@cpax.org.uk>
Date2015-06-11 00:34 +0100
Message-ID<mlahfh$6b8$1@dont-email.me>
In reply to#63168
On 11/06/15 00:27, Andrew Cooper wrote:
> On 10/06/2015 22:08, Richard Heathfield wrote:
>> I would draw the OP's attention to the omission of parentheses from the
>> operand of sizeof:
>>
>> ptr = malloc(n * sizeof *ptr);
>>
>> There is no more need to write sizeof(*ptr) than there is to write +(x).
>>
>
> While true, it quickly gets deceptive for more complicated expressions
> such as 'sizeof(*p)->foo', where sizeof evaluates to the size of foo,
> rather than the size of the object pointed to by p.

I don't see why this is deceptive, any more than +(*p)->foo is deceptive 
in comparison to +(*p)->foo.

Could you please explain why you think it's deceptive?

> You owe it to anyone who reads your code, not to add to the cognitive
> load of attempting to interpret it.

I would agree with you that the code should be as easy to read as is 
reasonably possible. I don't agree that adding redundant parentheses 
necessarily improves readability.

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#63172

FromRichard Heathfield <rjh@cpax.org.uk>
Date2015-06-11 00:38 +0100
Message-ID<mlahmt$6b8$3@dont-email.me>
In reply to#63170
On 11/06/15 00:34, Richard Heathfield wrote:

>
> I don't see why this is deceptive, any more than +(*p)->foo is deceptive
> in comparison to +(*p)->foo.

Oops. Of course I meant "in comparison to +((*p)->foo)".

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#63174 — Re: writing code for people who don't know the language (was: sizeof(arr[0]))

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2015-06-10 21:16 -0400
SubjectRe: writing code for people who don't know the language (was: sizeof(arr[0]))
Message-ID<ak5ex.100143$Mj.7041@fx18.iad>
In reply to#63170
On Wednesday June 10 2015 20:38, in comp.lang.c, "Stefan Ram"
<ram@zedat.fu-berlin.de> wrote:
[snip]
>   So they now even write:
> 
> while(( *p++ = *q++ )){ ; }

I sometimes write for() or while() loops with an empty compound statement, to
make the fact that the loop performs all the useful work more apparent.

For example, this code fragment searches an array for an element that matches
a specific value, and stops when either the matching element is found, or the
the end of the array has been reached:
  for (related = 0;
       related < nXref && this->SourceRecipeID != xref[related].pRB_RecipeId;
       ++related)
  {/*NOP*/}

The next statement tests the termination condition, and performs the
appropriate activity

In this pattern, the loop contains all the necessary logic, and the "looped"
statement is superfluous. I /could/ have just used a null-statement (;) but
the compound statement (with the embedded NOP comment) is a much-better
eyecatcher.


-- 
Lew Pitcher
"In Skills, We Trust"
PGP public key available upon request

[toc] | [prev] | [next] | [standalone]


#63175 — Re: writing code for people who don't know the language

FromRichard Heathfield <rjh@cpax.org.uk>
Date2015-06-11 02:35 +0100
SubjectRe: writing code for people who don't know the language
Message-ID<mlaoi7$fp5$1@dont-email.me>
In reply to#63170
On 11/06/15 01:38, Stefan Ram wrote:
> Richard Heathfield <rjh@cpax.org.uk> writes:
>>I would agree with you that the code should be as easy to read as is
>>reasonably possible. I don't agree that adding redundant parentheses
>>necessarily improves readability.
>
>    We are living in dumbed-down times!
>
>    Use »i++« in JavaScript, and »jslint« by Crockford will tell
>    you that this is »excessive trickiness«.

That's a curious way to describe something as bland as ++. I'd have 
thought the word "idiomatic" would be more appropriate.

>    A student in my Java course told me that he was not given a
>    job because in the interview he used »?:«, and the company
>    believed that this was unreadable (probably in their opinion
>    because nobody knows such »obscure operators«). (And they
>    also expected him to know this style rule of the company by
>    mind reading.)

A narrow escape.

>    They think »if« is much more readable for beginners than »?:«.
>    But whenever I show the following to beginners:
>
> char const * english( int const a )
> { char const * result;
>    if( a == 0 )result = "zero";
>    if( a == 1 )result = "one";
>    if( a == 2 )result = "two";
>    if( a == 3 )result = "three";
>    else        result = "four";
>    return result; }

You telegraphed it, so it was easy to spot. Whether it would have been 
quite so obvious if we hadn't been primed, I don't know.
<snip>

>    . When someone can't even read »?:« or »x++«, how do you expect
>    him to write any piece of non-trivial code, say code for OCR,
>    a compiler, or code to navigate a car through the streets?

Or indeed to tie his own shoelaces.

>    Or people writing
>
> while(( *p++ = *q++ ));
>
>    where the double parentheses are intended to avoid a warning message,
>    or even people saying that each inner statement in a while needs braces.
>    So they now even write:
>
> while(( *p++ = *q++ )){ ; }
>
>    because they believe that this will help someone who might insert
>    another statement into the loop not to forget the braces!

That one's not quite as ridiculous as you are trying to make it sound. 
In that particular case, you have a mild point, but in general there is 
actually a danger that this:

   while(foo(bar) > baz)
     quux = quuux(quuuux);

could be edited into this:

   while(foo(bar) > baz)
     initquuuux(&quuuux);
     quux = quuux(quuuux);

The probability that this mistake will occur does of course depend on 
the programmer, but the consequences if it does happen could be quite 
troublesome. It is not difficult to contrive circumstances in which the 
probability is increased:

* an editor that doesn't do line-wrap
* a while condition that stretches right across the visible window
* a programmer who is accustomed to a layout style that puts opening 
braces (and perhaps even closing braces) at the ends of lines
* a single-statement loop body that spans multiple lines

None of these conditions is particularly unlikely, and the combination 
could lead to an occurrence of this bug:

while((currdate = convert_date_to_julian(fund->pro| <- screen edge
   fund->projection->projected_balance += interest_|
   is_triversary(fund->projection_date) * fund->tri|
   is_charge_date(currdate) * fund->projection->ann|

Contrived? Of course. Possible? Certainly.

I habitually use braces even for single-statement loop bodies, to the 
point where I don't even think about it (except when hacking up a 
ten-liner, maybe, in which case I might stretch a point, but a quick 
review of a bunch of programs in my scratch directory would suggest that 
I don't stretch that point very far or very often).

I'm not actually all that worried about stopping bugs in this way, 
though. I got into the habit because I used to catch myself muttering 
whenever I was maintaining old code and had to add the braces, so I 
started putting them in 'up front' instead, which cured the muttering 
problem (for no logical reason that I can think of - after all, it takes 
just as long to put the braces in during initial development as it would 
during maintenance, so it hasn't actually saved me any time... unless, 
of course, it has stopped me from suffering instances of the bug 
mentioned above (and there's no way to tell that, one way or the other).

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#63182 — Re: writing code for people who don't know the language

FromBartc <bc@freeuk.com>
Date2015-06-11 11:16 +0100
SubjectRe: writing code for people who don't know the language
Message-ID<mlbn4e$nqf$1@dont-email.me>
In reply to#63175
On 11/06/2015 02:35, Richard Heathfield wrote:
> On 11/06/15 01:38, Stefan Ram wrote:
>> Richard Heathfield <rjh@cpax.org.uk> writes:
>>> I would agree with you that the code should be as easy to read as is
>>> reasonably possible. I don't agree that adding redundant parentheses
>>> necessarily improves readability.
>>
>>    We are living in dumbed-down times!
>>
>>    Use »i++« in JavaScript, and »jslint« by Crockford will tell
>>    you that this is »excessive trickiness«.
>
> That's a curious way to describe something as bland as ++. I'd have
> thought the word "idiomatic" would be more appropriate.

++ and --, when used inside expressions at least, I've always found 
fiddly to implement. They don't seem quite right to use either.

I do still use them, but it feels nearly as unsatisfactory as using goto.

For example, in constructions such as this:

  a[++n] = 0;
  b[n]   = 0;
  c[n]   = 0;

You have to be careful to increment n just once. If you start with 
a[++n]=0 and decide you need b[] updated too, you can't just copy that 
line and replace a with b; you have to fix that ++n.

And if you later decide you don't need a[] updated after all, that ++n 
now has to be inherited by the next line. Or if there is only a[], but 
you still need n incremented, now you need ++n. Or you want to assign 
c[n[ first. etc.

It's all a lot less troublesome just writing:

  ++n;        // apt comment that is out of place next to a[++n]
  a[n] = 0;
  b[n] = 0;
  c[n] = 0;

The assignments are more balanced too.

-- 
Bartc

[toc] | [prev] | [next] | [standalone]


#63183 — Re: writing code for people who don't know the language

FromBartc <bc@freeuk.com>
Date2015-06-11 11:29 +0100
SubjectRe: writing code for people who don't know the language
Message-ID<mlbnrj$qnj$1@dont-email.me>
In reply to#63170
On 11/06/2015 01:38, Stefan Ram wrote:

> char const * english( int const a )
> { char const * result;
>    if( a == 0 )result = "zero";
>    if( a == 1 )result = "one";
>    if( a == 2 )result = "two";
>    if( a == 3 )result = "three";
>    else        result = "four";
>    return result; }
>
> void print( int const a ){ puts( english( a )); }
>
> int main( void )
> { print( 0 ); print( 1 ); print( 2 ); print( 3 ); print( 4 ); }
>
>    , they tell me that it will print »zero«, »one«, »two«,
>    »three«, »four«! Can you all spot why it will not?
>
>    It's actually harder to make that mistake with »?:«;
>    and it's shorter:
>
> char const * english( int const a )
> { return
>    a == 0 ? "zero"  :
>    a == 1 ? "one"   :
>    a == 2 ? "two"   :
>    a == 3 ? "three" :
>             "four"; }


You think this is clearer? The correct way of writing your example is 
like this, if you only want one return point (and where actual code 
couldn't be better expressed as a switch or table look-up):

     if     ( a == 0 ) result = "zero";
     else if( a == 1 ) result = "one";
     else if( a == 2 ) result = "two";
     else if( a == 3 ) result = "three";
     else              result = "four";
     return result;

IMO, ?: should be used sparingly, and rarely nested, not if you want to 
make it obvious what is being done.

Your use of it in a large multi-line expression following the 'return' 
would raise a few eyebrows I think, when people have eventually spotted 
the return at the top of the function rather than at the end as is 
customary!

>    . When someone can't even read »?:« or »x++«, how do you expect
>    him to write any piece of non-trivial code, say code for OCR,
>    a compiler, or code to navigate a car through the streets?

I'm sure all those have been done by people who have no idea what ?: is 
at all.

-- 
Bartc

[toc] | [prev] | [next] | [standalone]


#63184 — Re: writing code for people who don't know the language

Fromgazelle@shell.xmission.com (Kenny McCormack)
Date2015-06-11 11:43 +0000
SubjectRe: writing code for people who don't know the language
Message-ID<mlbs8f$7lv$1@news.xmission.com>
In reply to#63183
In article <mlbnrj$qnj$1@dont-email.me>, Bartc  <bc@freeuk.com> wrote:
...
>You think this is clearer? The correct way of writing your example is 
>like this, if you only want one return point (and where actual code 
>couldn't be better expressed as a switch or table look-up):
>
>     if     ( a == 0 ) result = "zero";
>     else if( a == 1 ) result = "one";
>     else if( a == 2 ) result = "two";
>     else if( a == 3 ) result = "three";
>     else              result = "four";
>     return result;

No, the *right* way to do this is:

    /* Initializations of "numstrings" array not shown */

    return numstrings[a];

That's the way I usually end up organizing these sorts of problems.

-- 

There are many self-professed Christians who seem to think that because
they believe in Jesus' sacrifice they can reject Jesus' teachings about
how we should treat others. In this country, they show that they reject
Jesus' teachings by voting for Republicans.

[toc] | [prev] | [next] | [standalone]


#63252

FromPaul N <gw7rib@aol.com>
Date2015-06-14 13:13 -0700
Message-ID<e3facbc9-28e1-4832-9d49-e0ea653c1d1a@googlegroups.com>
In reply to#63170
On Thursday, 11 June 2015 00:34:29 UTC+1, Richard Heathfield  wrote:
> On 11/06/15 00:27, Andrew Cooper wrote:
> > On 10/06/2015 22:08, Richard Heathfield wrote:
> >> I would draw the OP's attention to the omission of parentheses from the
> >> operand of sizeof:
> >>
> >> ptr = malloc(n * sizeof *ptr);
> >>
> >> There is no more need to write sizeof(*ptr) than there is to write +(x).
> >>
> >
> > While true, it quickly gets deceptive for more complicated expressions
> > such as 'sizeof(*p)->foo', where sizeof evaluates to the size of foo,
> > rather than the size of the object pointed to by p.
> 
> I don't see why this is deceptive, any more than +(*p)->foo is deceptive 
> in comparison to +(*p)->foo.
> 
> Could you please explain why you think it's deceptive?

If I saw 'sizeof(*p)->foo', my first thought would be along the lines of "That's wrong! Sizeof returns a size_t, how on earth can you feed that into a -> ?". I would tend to expect size_of(summat) to return the size of whatever summat was.

[toc] | [prev] | [next] | [standalone]


#63265

FromPhilip Lantz <prl@canterey.us>
Date2015-06-14 17:52 -0700
Message-ID<MPG.2fe7c1a8b7cdfb1d36@news.eternal-september.org>
In reply to#63252
Stefan Ram wrote:
> 
> Paul N <gw7rib@aol.com> writes:
> >On Thursday, 11 June 2015 00:34:29 UTC+1, Richard Heathfield  wrote:
> >>Could you please explain why you think it's deceptive?
> >If I saw 'sizeof(*p)->foo', my first thought would be along
> >the lines of "That's wrong! Sizeof returns a size_t, how on
> >earth can you feed that into a -> ?". I would tend to expect
> >size_of(summat) to return the size of whatever summat was.
> 
>   So, it's »deceptive« to people who don't know C.
> 
>   What about people who know C?

Not deceptive. However, I would prefer it with a space after sizeof.

[toc] | [prev] | [next] | [standalone]


#63304

From"Bill Cunningham" <nospam@nspam.invalid>
Date2015-06-15 14:26 -0400
Message-ID<mln5an$q1$1@dont-email.me>
In reply to#63170
"Richard Heathfield" <rjh@cpax.org.uk> wrote in message 
news:mlahfh$6b8$1@dont-email.me...

> I would agree with you that the code should be as easy to read as is 
> reasonably possible. I don't agree that adding redundant parentheses 
> necessarily improves readability.

    Indeed. For the earlier code I think *p is a int * isn't it? That 
wouldn't need parenthesis at all I wouldn't think. Isn't it not really a 
built in type? Like sizeof (int p);

Bill

[toc] | [prev] | [next] | [standalone]


#63305

FromRichard Heathfield <rjh@cpax.org.uk>
Date2015-06-15 19:34 +0100
Message-ID<mln5pk$2vb$1@dont-email.me>
In reply to#63304
On 15/06/15 19:26, Bill Cunningham wrote:
> "Richard Heathfield" <rjh@cpax.org.uk> wrote in message
> news:mlahfh$6b8$1@dont-email.me...
>
>> I would agree with you that the code should be as easy to read as is
>> reasonably possible. I don't agree that adding redundant parentheses
>> necessarily improves readability.
>
>      Indeed. For the earlier code I think *p is a int * isn't it?

In the original code, p is an int *, so *p is an int. But it hardly 
matters - it could be any complete object type. In fact, that's the 
whole point. The pattern:

T *new = malloc(n * sizeof *new);

works correctly, whether T is int, float, time_t, or struct { char ch; 
long i; double d; int (*func)(const char *); }

> That
> wouldn't need parenthesis at all I wouldn't think. Isn't it not really a
> built in type? Like sizeof (int p);

int is indeed a built-in type, but sizeof (int p) is merely a syntax 
error. If you mean the size of p, use sizeof p. If you mean the size of 
the type of object pointed to by p, use sizeof *p.

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#63308

From"Bill Cunningham" <nospam@nspam.invalid>
Date2015-06-15 14:55 -0400
Message-ID<mln6vt$893$1@dont-email.me>
In reply to#63305
"Richard Heathfield" <rjh@cpax.org.uk> wrote in message 
news:mln5pk$2vb$1@dont-email.me...

> int is indeed a built-in type, but sizeof (int p) is merely a syntax 
> error. If you mean the size of p, use sizeof p. If you mean the size of 
> the type of object pointed to by p, use sizeof *p.

    I thought sizeof (int p) kind of looked funny. One could use sizeof 
(int) too I would suppose. So sizeof *p is saying sizeof the "point to int" 
or is the * a dereference here? But he's wanting a "dynamic array" so the 
size needs to change in the code at the applicable place.

    That bring up to me something else. What about sizeof (int *) is that 
valid? I know I should know, but I have so many other things to do too.

Bill

[toc] | [prev] | [next] | [standalone]


#63309

FromMelzzzzz <melz@zzzzz.com>
Date2015-06-15 20:59 +0200
Message-ID<20150615205924.35d02dfb@maxa-pc>
In reply to#63308
On Mon, 15 Jun 2015 14:55:08 -0400
"Bill Cunningham" <nospam@nspam.invalid> wrote:

> 
> "Richard Heathfield" <rjh@cpax.org.uk> wrote in message 
> news:mln5pk$2vb$1@dont-email.me...
> 
> > int is indeed a built-in type, but sizeof (int p) is merely a
> > syntax error. If you mean the size of p, use sizeof p. If you mean
> > the size of the type of object pointed to by p, use sizeof *p.
> 
>     I thought sizeof (int p) kind of looked funny. One could use
> sizeof (int) too I would suppose. So sizeof *p is saying sizeof the
> "point to int" or is the * a dereference here? But he's wanting a
> "dynamic array" so the size needs to change in the code at the
> applicable place.
> 
>     That bring up to me something else. What about sizeof (int *) is
> that valid? I know I should know, but I have so many other things to
> do too.
> 
> Bill
> 
> 

sizeof is runtime evaluated only on VLA's.

[toc] | [prev] | [next] | [standalone]


Page 1 of 5  [1] 2 3 4 5  Next page →

Back to top | Article view | comp.lang.c


csiph-web