473,626 Members | 3,183 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inflexible array members

Hi all,

One cannot return a pointer to an array type in C because C has no first
class array types. But one can return a pointer to a struct containing an
incomplete array via the illegal but widely supported zero array struct
hack:

#include <stdlib.h>

typedef struct byte_vector_t byte_vector_t;

struct byte_vector_t {
unsigned char byte[0];
};

int main() {
byte_vector_t *byte_vector=ma lloc(10);
byte_vector->byte[9]=42;
return 0;
}

It is frequently stated that flexible array members are a substitute for
the zero array struct hack. Let's see (by compiling file array.c below
with GNU C):

#include <stdlib.h>

typedef struct byte_vector_t byte_vector_t;

struct byte_vector_t {
unsigned char byte[];
};

int main() {
byte_vector_t *byte_vector=ma lloc(10);
byte_vector->byte[9]=42;
return 0;
}

$ gcc -std=c99 array.c
array.c:6: error: flexible array member in otherwise empty struct

GCC refuses to compile this code because C99 states (6.7.2.1,
paragraph 2):

A structure or union shall not contain a member with incomplete or
function type (hence, a structure shall not contain an instance of
itself, but may contain a pointer to an instance of itself), except
that the last member of a structure with more than one named member may
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^
have incomplete array type; such a structure (and any union containing,
possibly recursively, a member that is such a structure) shall not be a
member of a structure or an element of an array.

This restriction is repeated in paragraph 16.

The struct types are intended to serve as self-documenting code and stop
me from incorrectly indexing a pointer to a single value (and vice versa).
Typedefs also lead to self-documenting code but provide no additional
compile-time type safety.

Is this restriction upon flexible array members sensible? The core syntax
and semantics are better because one should not index past the elements of
an array (and a zero sized array has no elements). Is there a standard way
I can maintain the extra type safety of structs with an incomplete array
member without having to pad those structs with a non-zero sized header?

Many thanks,
Adam
Jul 8 '06 #1
26 3385
Adam Warner wrote:
Hi all,

One cannot return a pointer to an array type in C because C has no first
class array types.
Sure you can. Typically, you won't really want to, but it's possible.

typedef char array[10];
array *f(void) {
/* ... */
}

You can also write it without a typedef as

char (*f(void))[10] {
/* ... */
}

You can also leave out the size.

typedef char array[];
array *f(void) {
/* ... */
}

or

char (*f(void))[] {
/* ... */
}

The rest of your message seems irrelevant after that.

Jul 8 '06 #2
On Sat, 08 Jul 2006 00:32:05 -0700, Harald van Dijk wrote:
Adam Warner wrote:
>Hi all,

One cannot return a pointer to an array type in C because C has no first
class array types.

Sure you can. Typically, you won't really want to, but it's possible.

typedef char array[10];
array *f(void) {
/* ... */
}

You can also write it without a typedef as

char (*f(void))[10] {
/* ... */
}

You can also leave out the size.

typedef char array[];
array *f(void) {
/* ... */
}

or

char (*f(void))[] {
/* ... */
}
Excellent! Thank you for the correction.

#include <stdint.h>
#include <stdlib.h>

typedef uint8_t octet_vector_t[];

int main() {
octet_vector_t *vector=malloc( 10);
(*vector)[9]=42;
return 0;
}

Please let me known if there's a way to avoid the explicit dereferencing
syntax for every array access.

Regards,
Adam
Jul 8 '06 #3
Adam Warner wrote:
On Sat, 08 Jul 2006 00:32:05 -0700, Harald van Dijk wrote:
Adam Warner wrote:
Hi all,

One cannot return a pointer to an array type in C because C has no first
class array types.
Sure you can. Typically, you won't really want to, but it's possible.

Excellent! Thank you for the correction.

Please let me known if there's a way to avoid the explicit dereferencing
syntax for every array access.
"Typically, you won't really want to." If you use a pointer to an
array's first element instead of one to the whole array, which is what
most functions accepting or returning arrays do, you won't have that
problem. Is there a reason that is not an option for you?

Jul 8 '06 #4
Harald van Dijk wrote:
Adam Warner wrote:
On Sat, 08 Jul 2006 00:32:05 -0700, Harald van Dijk wrote:
Adam Warner wrote:
>Hi all,
>>
>One cannot return a pointer to an array type in C because C has no first
>class array types.
>
Sure you can. Typically, you won't really want to, but it's possible.
Excellent! Thank you for the correction.

Please let me known if there's a way to avoid the explicit dereferencing
syntax for every array access.

"Typically, you won't really want to." If you use a pointer to an
array's first element instead of one to the whole array, which is what
most functions accepting or returning arrays do, you won't have that
problem. Is there a reason that is not an option for you?
To clarify, I mean with typedefs.

Jul 8 '06 #5
On Sat, 08 Jul 2006 03:22:24 -0700, Harald van Dijk wrote:
Harald van Dijk wrote:
>Adam Warner wrote:
On Sat, 08 Jul 2006 00:32:05 -0700, Harald van Dijk wrote:
Adam Warner wrote:
Hi all,

One cannot return a pointer to an array type in C because C has no first
class array types.

Sure you can. Typically, you won't really want to, but it's possible.

Excellent! Thank you for the correction.

Please let me known if there's a way to avoid the explicit dereferencing
syntax for every array access.

"Typically, you won't really want to." If you use a pointer to an
array's first element instead of one to the whole array, which is what
most functions accepting or returning arrays do, you won't have that
problem. Is there a reason that is not an option for you?

To clarify, I mean with typedefs.
From my perspective a type system should distinguish between a scalar and
a vector and not permit one to be misused as the other without an explicit
type cast (though a scalar can be abstracted as the first element of a
vector of length 1).

The declaration "int *var;" is conceptually a pointer to a scalar of type
int or a pointer to a vector of type int. If it's a scalar it should never
be positively indexed as an array yet var[12345] will silently compile.

So let's explicitly define scalars as vectors of length 1:

#include <stdlib.h>

typedef unsigned char byte_t[1];

int main() {
byte_t *b=malloc(1);
(*b)[1]=123;
return 0;
}

$ gcc -std=c99 -Wall -Wextra array.c
$

This compiles without a single warning that the static indexing is out of
bounds.

There is a solution: If every scalar is defined within a struct then the
scalar cannot be mistaken for an array of scalars. This does have
implications for inefficient ABIs that return all structs, no matter how
small, via pointers to memory.

Regards,
Adam
Jul 8 '06 #6
Adam Warner wrote:
From my perspective a type system should distinguish between a scalar and
a vector and not permit one to be misused as the other without an explicit
type cast (though a scalar can be abstracted as the first element of a
vector of length 1).
Ah, sorry, I don't think that's possible in standard C. Pointer
arithmetic is allowed for any pointer to a complete object type,
there's no way around that other than by not using a complete object
type, which is not an appropriate solution in most cases.

Jul 8 '06 #7
Adam Warner posted:

Excellent!

Here's a recent thread about declarations which might interest you:
http://groups.google.ie/group/comp.l...454781f0d9831/
f0276049c354479 f?hl=en#f027604 9c354479f
--

Frederick Gotham
Jul 8 '06 #8
On Sat, 08 Jul 2006 23:42:22 +1200, in comp.lang.c , Adam Warner
<us****@consult ing.net.nzwrote :
>The declaration "int *var;" is conceptually a pointer to a scalar of type
int or a pointer to a vector of type int.
Er, no its not. Its conceptually a pointer to a block of memory
containing objects of type int.

Its not a pointer to a vector of anything.
>If it's a scalar it should never be positively indexed as an array yet var[12345] will silently compile.
Sure, because what it points to is a block of memory.

(snip example of array bounds overrun)
>This compiles without a single warning that the static indexing is out of
bounds.
So? Its the programmer's responsibility not to break the rules.
>There is a solution:
Indeed there are many. There is however a penalty, often quite a
severe one.

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jul 8 '06 #9
On Sat, 08 Jul 2006 17:02:25 +0100, Mark McIntyre wrote:
(snip example of array bounds overrun)
Here's that code example again:

#include <stdlib.h>

typedef unsigned char byte_t[1];

int main() {
byte_t *b=malloc(1);
(*b)[1]=123;
return 0;
}

$ gcc -std=c99 -Wall -Wextra array.c
$
>>This compiles without a single warning that the static indexing is out
of bounds.

So? Its the programmer's responsibility not to break the rules.
Here we have an explicit type definition that byte_t is an unsigned char
array of length 1 and you don't even care about silent compilation of a
STATICALLY OBVIOUS buffer overrun.

Third parties suffer from programmers unintentionally breaking rules.
C programming is like having a car with the speedometer removed and a gas
pedal that keeps getting stuck. Yet drivers of these cars are mystified
why others don't want them on the road.

Regards,
Adam
Jul 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
7052
by: Olumide | last post by:
Thats the question. I know about virtual memory, and the MMU. I just wonder if array members guaranteed to be contiguous in physical memory (and if so, why). Thanks, Olumide
4
10171
by: Peter Olcott | last post by:
Is this possible in C++ ???
0
367
by: Adam Warner | last post by:
Hi all, One cannot return a pointer to an array in C since there are no first class array types. But one can return a pointer to an incomplete array via the illegal but widely supported zero array struct hack: #include <stdlib.h> typedef struct byte_vector_t byte_vector_t;
0
8265
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8196
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8364
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5574
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4092
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4197
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.