473,770 Members | 2,153 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer to flexible array of structures in other structure

I'm trying to put pointer to flexible array of structures in other
structure. I want to have pointer to array of pixels in screen
structure. Here is mine code, but I think it isn't quite all right:

struct pixel
{
int x;
int y;
int color;
};

struct display
{
pixel *screen;
};

Now I would like to do something like that (to have screen made of 10
pixels):

struct display scr;
scr.screen = (struct pixel*)malloc(1 0*(sizeof(struc t pixel)));
scr.screen[0].x = 10;

and it is working, but what is worrying also
scr.screen[11].x = 10;

or
scr.screen[100].x = 10;

is working. I don't now what is wrong. I'm not sure but I think I'm
making mistake when defining structures. How should I define flexible
array of structures in structure? And how should I point it?

Thanks for help and Merry Xmas,
John

Dec 23 '05 #1
8 2471
ulyses wrote:

I'm trying to put pointer to flexible array of structures in other
structure. I want to have pointer to array of pixels in screen
structure. Here is mine code, but I think it isn't quite all right:

struct pixel
{
int x;
int y;
int color;
};

struct display
{
pixel *screen;
};

Now I would like to do something like that (to have screen made of 10
pixels):

struct display scr;
scr.screen = (struct pixel*)malloc(1 0*(sizeof(struc t pixel)));
1) Don't cast the return from malloc(), as it only hides the error of
forgetting the proper header file.

2) Rather than take sizeof(struct pixel), a "better" solution is to
use "sizeof(*scr.sc reen)", as this allows scr.screen to change.

scr.screen = malloc(10*sizeo f(*scr.screen)) ;

3) Don't forget to check the return for NULL.
scr.screen[0].x = 10;

and it is working, but what is worrying also
scr.screen[11].x = 10;

or
scr.screen[100].x = 10;

is working. I don't now what is wrong. I'm not sure but I think I'm
making mistake when defining structures. How should I define flexible
array of structures in structure? And how should I point it?


What's "wrong" is your expectation that C will do the bounds checking
for you, which it does not. If you need this, then you should store
the number of pixels allocated:

struct display
{
int numpixel;
struct pixel *screen;
};

After allocating scr.screen, set scr.numpixel to the number of pixels
allocated. You then need to do your own bounds checking, perhaps
through a function:

[Note: Risking public humiliation by posting untested code.]

pixel *GetPixel(struc t display *pdisp, int subscript)
{
ASSERT(subscrip t >= 0 && subscript < pdisp->numpixel);
return(&pdisp->screen[subscript]);
}

Now, if you attempt:

GetPixel(&scr,1 00)->x = 10;

you will get an assertion error.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Dec 23 '05 #2
I see. Thanks for your help Kenneth. Still one thing is interesting.
How can scr.screen[100].x = 10 work when the array's size is 10? What
is more I can get the value using scr.screen[100].x, e.g. for printf.

Where is this put in the memory, when only 10 'positions' are alocated?
Is it placed somewhere in memory and for example some other app can
erease it?

Dec 23 '05 #3
"ulyses" <ul****@autogra f.pl> writes:
I'm trying to put pointer to flexible array of structures in other
structure. I want to have pointer to array of pixels in screen
structure. Here is mine code, but I think it isn't quite all right:

struct pixel
{
int x;
int y;
int color;
};

struct display
{
pixel *screen;
};
There's a problem here. You've defined a type called "struct pixel";
there is no type called "pixel". This should be

struct pixel *screen;

<OT>
In C++ the type "struct pixel" can be referred to as "pixel", but if
you were programming in C++ you'd have posted to comp.lang.c++,
wouldn't you?
</OT>
Now I would like to do something like that (to have screen made of 10
pixels):

struct display scr;
scr.screen = (struct pixel*)malloc(1 0*(sizeof(struc t pixel)));
scr.screen[0].x = 10;

and it is working,
So far, so good, except that the cast on the malloc() is unnecessary
and can mask errors such as forgetting to "#include <stdlib.h>" or
compiling your C code with a C++ compiler. If you get an error
message without the cast, you need to fix the error, not hide it
with a cast that says to the compiler, "Shut up, I know what I'm doing".

The recommended style is

str.screen = malloc(10 * *scr.screen);

By not referring to the type "struct pixel" in the malloc() call, you
don't need to change the call if the type of scr.screen changes later
on.
but what is worrying also
scr.screen[11].x = 10;

or
scr.screen[100].x = 10;

is working. I don't now what is wrong. I'm not sure but I think I'm
making mistake when defining structures. How should I define flexible
array of structures in structure? And how should I point it?


No, "scr.screen[11].x = 10;" is not "working". It's clobbering memory
beyond the end of your array, which invokes undefined behavior. That
means anything can happen, including having it appear to "work".

C doesn't allow you to index beyond the end of an array object, but it
doesn't do anything to prevent you from doing so. If you index past
the end of an array anyway, the compiler isn't obliged to do anything
about it. It's entirely your responsibility to stay within the bounds
of your object. This allows better performance when you don't make
mistakes, at the expense of arbitrarily bad behavior when you do make
mistakes.

You should probably have a second member in your "struct display" that
keeps track of how many pixels you've allocated. For example:

struct pixel
{
int x;
int y;
int color;
};

struct display
{
struct pixel *screen;
size_t pixel_count;
};

struct display scr;
scr.screen = malloc(10 * sizeof *scr.screen);
if (scr.screen == NULL) {
scr.pixel_count = 0; /* malloc failed */
}
else {
scr.pixel_count = 10;
}
The allocation and initialization should probably be encapsulated in a
function that takes the number of pixels as an argument. You might
want more elaborate error handling as well.

What you have so far is a decent starting point, but there are a few
things you should think about as you develop it further.

I find the use of the terms "screen" and "display" confusing. They
tend to be nearly synonymous in my mind, but you're not using them
consistently as far as I can tell. "display" is the name of the
structure, "screen" is the name of the member of that structure that
points to the array of pixels, but "scr", an abbreviation of "screen",
is also the name of an object of type 'struct display". Pick a
consistent naming scheme now, before your program becomes too
complicated to go back and fix.

Also, a screen/display is more than a linear array of pixels. You're
going to want to keep track of the horizontal and vertical dimensions,
i.e., you'll need a dynamic 2-dimensional array. Section 6 of the
comp.lang.c FAQ has some good tips on this.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Dec 23 '05 #4
"ulyses" <ul****@autogra f.pl> writes:
I see. Thanks for your help Kenneth. Still one thing is interesting.
How can scr.screen[100].x = 10 work when the array's size is 10? What
is more I can get the value using scr.screen[100].x, e.g. for printf.


Please provide context when you post a followup. See
<http://cfaj.freeshell. org/google/> for instructions on how to do this
in spite of Google's broken interface.

Given that scr.screen points to a 10-element array,
scr.screen[100].x= 10
doesn't "work". It probably clobbers memory outside the allocated
bounds of the object, invoking undefined behavior. If it happens that
the clobbered memory is within your program's address space, and isn't
currently being used, it can appear to "work". If you're lucky, the
program will crash when you try to do this. Unfortunately, there are
no guarantees. It's your job to avoid doing this.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Dec 24 '05 #5
Thanks Keith, now everything seems clear. I think that your last post
solves the whole problem. Thanks to Kenneth also.

John

Dec 24 '05 #6
"ulyses" <ul****@autogra f.pl> writes:
Thanks Keith, now everything seems clear. I think that your last post
solves the whole problem. Thanks to Kenneth also.


And again:

Please provide context when you post a followup. See
<http://cfaj.freeshell. org/google/> for instructions on how to do this
in spite of Google's broken interface.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Dec 24 '05 #7
On Fri, 23 Dec 2005 23:41:20 GMT, Keith Thompson <ks***@mib.or g>
wrote:
"ulyses" <ul****@autogra f.pl> writes:
scr.screen = (struct pixel*)malloc(1 0*(sizeof(struc t pixel)));

The recommended style is

str.screen = malloc(10 * *scr.screen);

Not quite. (Missing 'sizeof'.)

<snip rest>

- David.Thompson1 at worldnet.att.ne t
Jan 4 '06 #8
Dave Thompson <da************ *@worldnet.att. net> writes:
On Fri, 23 Dec 2005 23:41:20 GMT, Keith Thompson <ks***@mib.or g>
wrote:
"ulyses" <ul****@autogra f.pl> writes:

> scr.screen = (struct pixel*)malloc(1 0*(sizeof(struc t pixel)));

The recommended style is

str.screen = malloc(10 * *scr.screen);

Not quite. (Missing 'sizeof'.)

<snip rest>


Quite right, I don't know how I missed that.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Jan 4 '06 #9

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

Similar topics

8
54447
by: Frank Münnich | last post by:
Hi there.. My name is Frank Münnich. I've got a question about pointers that refer to an array of a structure. How do I declare that type? If I have declared a structure struct mystruc { int x,y,z; char a,b,c;
20
2117
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct udpiphdr *ui; struct ip *ip; ip = (struct ip *) buf;
10
6695
by: Adam Warner | last post by:
Hi all, With this structure that records the length of an array of pointers as its first member: struct array { ptrdiff_t length; void *ptr; };
2
10326
by: Christopher Benson-Manica | last post by:
Is the following program conforming under C99? #include <stdio.h> typedef struct foo { int bar; int baz; } foo; foo foos={
6
1776
by: Angel | last post by:
I'm exporting (with DllImport) a C-style function with this syntax: int z9indqry (4_PARM *parm); 4_PARM is a structure declared in a proprietary header file that cannot be included in my project (due to C# limits). What would be the other best way to do this? I would like to be able to use the original struct because these structs have over 40 members each and there are several more Structs similar to 4_PARM. Also, they are modified...
7
2807
by: Kathy Tran | last post by:
Hi, Could you please help me how to declare an araay of pointer in C#. In my program I declared an structure public struct SEventQ { public uint uiUserData; public uint uiEvent; public uint uiParam0; public uint uiParam1;
12
3885
by: gcary | last post by:
I am having trouble figuring out how to declare a pointer to an array of structures and initializing the pointer with a value. I've looked at older posts in this group, and tried a solution that looked sensible, but it didn't work right. Here is a simple example of what I'm trying to accomplish: // I have a hardware peripheral that I'm trying to access // that has two ports. Each port has 10 sequential // registers. Create a...
10
2213
by: haomiao | last post by:
I want to implement a common list that can cantain any type of data, so I declare the list as (briefly) --------------------------------------- struct list { int data_size; int node_num; char nodes; //will be list_node1,list_node2... };
7
6993
by: edsunder | last post by:
I'm making a "wrapper" for an unmanaged DLL (written, I'm fairly certain in C). I have a c++ "wrapper" that I'm trying to convert to VB.net. I've got most of the program working, but I've hit a brick wall. I'm trying to convert the following two structures from their c++ versions to their vb.net versions. I cannot be sure which is the problem because both must be passed at the same time. The error I am getting is thrown by the object and...
0
9591
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
9425
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
10057
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10002
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
9869
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7415
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
6676
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
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.