473,796 Members | 2,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

2D array of structures

Hello,

I wonder how to resize such array of structures using realloc()?

#include <stdio.h>
#include <stdlib.h>
#define FIRST 7

typedef struct {
char *name;
int i;
int j;
} STRUCTURE;

STRUCTURE **p_structure;

int main() {

p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
if ( p_structure == NULL ) {
printf("Failed to allocate memory, exiting...");
return 1;
}
}

Thank you in advance

Svata

Nov 7 '06 #1
44 5820
svata <sv******@centr um.czwrote:
I wonder how to resize such array of structures using realloc()?
#include <stdio.h>
#include <stdlib.h>
#define FIRST 7
typedef struct {
char *name;
int i;
int j;
} STRUCTURE;
STRUCTURE **p_structure;
int main() {
Make that

int main( void )

since your main() takes no arguments.
p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
Don't cast the return value of malloc(), it only hides your mistake
should you have forgotten to include <stdlib.h>. But, more important,
you allocate here memory for 7 (FIRST) such structures. malloc() returns
a pointer to the start of this memory, which is of type 'STRUCTURE *'
(malloc() actually returns a void pointer but "STRUCTURE *' is the
correct type of a pointer to that memory). But you assign it instead
to a pointer that has type 'STRUCTURE **'. That, combined with your
use of the words "2D array" in the subjct line, leads to the suspicion
that you actually don't want to allocate memory for something that has
similar properties as an array of stuctures, but something more compli-
cated and similar to a 2D array of such structures. And that's what you
definitely won't get with that allocation, whatever the type of the
pointer you assign the return value of malloc() to. So, instead of
starting to guess what you might have intended I think it's better to
ask you to specify a bit more clearly what you intend to do here: do
you just want memory for a simple set of structures or do you want
something like a 2D array of such structures. In the first case you
could "repair" your program by simply defining 'p_structure' as

STTRUCTURE *p_structure;

Perhaps you thenn also might want to replace the line for the allo-
cation by

p_structure = malloc(FIRST * sizeof *p_structure);

because that way you don't have to change that line anymore if you
should decide to change the type of 'p_structure' sometime later.

You also write something about realloc() but I can't see any
use or mentioning of realloc() in the code you posted. But, of
course, you can use realloc() to resize the amount of memory
you obtained from malloc() - that's what realloc() was invented
for.
if ( p_structure == NULL ) {
printf("Failed to allocate memory, exiting...");
return 1;
}
It's good to see that you check that what malloc() returned!
}
Since main() returns an int, here's a missing line with a return
value...
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Nov 7 '06 #2
Jens Thoms Toerring wrote:
svata <sv******@centr um.czwrote:
<snip>
>p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
<snip>
correct type of a pointer to that memory). But you assign it instead
to a pointer that has type 'STRUCTURE **'. That, combined with your
use of the words "2D array" in the subjct line, leads to the suspicion
that you actually don't want to allocate memory for something that has
similar properties as an array of stuctures, but something more compli-
cated and similar to a 2D array of such structures. And that's what you
<snip>

I agree with what you've said, but the OP should also read section 6 of
the comp.lang.c FAQ before posting back here. Section 6 includes ways of
dynamically allocating space for things that work like 2D arrays. The
FAQ can be found at http://c-faq.com/
--
Flash Gordon
Nov 7 '06 #3
svata:
STRUCTURE **p_structure;

This is a pointer to a pointer to a STRUCTURE.

(I'm against the use of ALL CAPS for anything other than macros)

int main() {

p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));

This doesn't make sense.

You have a pointer to a pointer to a STRUCTURE. This would suggest to me
that you're going to store either of the following in it:

(1) The address of a pointer to a STRUCTURE.
(2) The address of the first element of an array, whereby each element
is a pointer to a STRUCTURE.

If it were either of the two above, the "malloc" invocation should look
something like:

p_structure = malloc( sizeof(STRUCTUR E*) );
or:
p_structure = malloc( 12 * sizeof(STRUCTUR E*) );

Note that I use the size of a "STRUCTURE* " rather than the size of a
"STRUCTURE" .

Of course, it's better to write the two of them as:

p_structure = malloc(sizeof*p );

p_structure = malloc(12 * sizeof*p);

--

Frederick Gotham
Nov 7 '06 #4
svata wrote:
>
I wonder how to resize such array of structures using realloc()?

#include <stdio.h>
#include <stdlib.h>
#define FIRST 7

typedef struct {
char *name;
int i;
int j;
} STRUCTURE;

STRUCTURE **p_structure;
Too many *s here.
>
int main() {
You
>
p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));
and here. Also _never_ cast the return from malloc (it only hides
errors without fixing them). You want:

p_structure = malloc(FIRST * sizeof *p_structure);
if ( p_structure == NULL ) {
printf("Failed to allocate memory, exiting...");
return 1;
}
}
You can then change the size to, say, SECOND with:

STRUCTURE *tmp; /* in a suitable location, not here */

if (tmp = realloc(p_struc ture, SECOND) p_structure = tmp;
else {
/* handle lack of memory */
}

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Nov 7 '06 #5
Hello Frederick,

I know it doesn't make sense. I was wrong in my assumption.
I should use p_structure = (STRUCTURE **) malloc(FIRST *
sizeof(STRUCTUR E*));

but anyway... should rather use array of structures.
typedef structure {
code goes here...
} _structure;

_structure *p_structure;
// and then malloc()

p_structure = malloc( INT * sizeof(_structu re));

if am I right?

svata

Frederick Gotham wrote:
STRUCTURE **p_structure;


This is a pointer to a pointer to a STRUCTURE.

(I'm against the use of ALL CAPS for anything other than macros)

int main() {

p_structure = (STRUCTURE **) malloc(FIRST * sizeof(STRUCTUR E));


This doesn't make sense.
--

Frederick Gotham
Nov 9 '06 #6
svata wrote:
Hello Frederick,

I know it doesn't make sense. I was wrong in my assumption.
I should use p_structure = (STRUCTURE **) malloc(FIRST *
sizeof(STRUCTUR E*));
No, you shouldn't: it's wiser to drop the unnecessary cast an
to ensure that the thing you sizeof is appropriate for the
pointer:

pStructure = malloc( FIRST * sizeof (*pStructure) );

which will (try to) mallocate space for FIRST (horrid name)
lumps of space adequate for the kinds of thing that
pStructure points to.
but anyway... should rather use array of structures.
Yes, get rid of the unnecessary layer of indirection.
typedef structure {
code goes here...
} _structure;
There are two things wrong with this. One is that it's
syntax is broken, since you spelt "struct" "structure" .
The other is that so many names beginning with _ are
reserved to the implementation it's unwise for you to
define /any/ name that does. So don't.

If you /must/ use a typedef for a structure -- you don't
need to, and some wise people argue that you shouldn't
(although others argue that those arguments aren't
convincing) -- you should also give it a /sensible/
name. "structure" isn't.

typedef struct yourStructTagHe re
{
int x;
int y;
} Point;

--
Chris ".enable proofreading" Dollin
The "good old days" used to be much better.

Nov 9 '06 #7
Chris Dollin wrote:

I learn by doing. So I will see what results I get.
pStructure = malloc( FIRST * sizeof (*pStructure) );

which will (try to) mallocate space for FIRST (horrid name)
lumps of space adequate for the kinds of thing that
pStructure points to.
but anyway... should rather use array of structures.

Yes, get rid of the unnecessary layer of indirection.
typedef structure {
code goes here...
} _structure;

There are two things wrong with this. One is that it's
syntax is broken, since you spelt "struct" "structure" .
The other is that so many names beginning with _ are
reserved to the implementation it's unwise for you to
define /any/ name that does. So don't.

If you /must/ use a typedef for a structure -- you don't
need to, and some wise people argue that you shouldn't
(although others argue that those arguments aren't
convincing) -- you should also give it a /sensible/
name. "structure" isn't.

typedef struct yourStructTagHe re
{
int x;
int y;
} Point;

--
Chris ".enable proofreading" Dollin
The "good old days" used to be much better.
Nov 9 '06 #8
I always use google to search an answer, but often results are not
relevant.
svata
>
I agree with what you've said, but the OP should also read section 6 of
the comp.lang.c FAQ before posting back here. Section 6 includes ways of
dynamically allocating space for things that work like 2D arrays. The
FAQ can be found at http://c-faq.com/
--
Flash Gordon
Nov 9 '06 #9
svata said:
Chris Dollin wrote:

I learn by doing. So I will see what results I get.
That's fine sometimes, but there are also times when it's best to learn from
other people's knowledge and experience. If you learn C "by doing", you're
likely to end up doing lots of things that aren't correct, but which happen
to behave in a particular way on your current system. Switch systems, and
all your code breaks. Oops.

Chris is an expert on C. Listen to Chris.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: normal service will be restored as soon as possible. Please do not
adjust your email clients.
Nov 9 '06 #10

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

Similar topics

8
1961
by: michi | last post by:
Hello everybody, I have following problem: I have an array of pointers to structures: table* tab = new table; and structure table is like this: struct table{ CSLL::node* chain;
4
7298
by: emma middlebrook | last post by:
Hi Straight to the point - I don't understand why System.Array derives from IList (given the methods/properties actually on IList). When designing an interface you specify a contract. Deriving from an interface and only implementing some of it means something is wrong: either the interface specification is wrong e.g. not minimal or the derivation is wrong e.g. the type can't actually honour this contract.
8
2474
by: ulyses | last post by:
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; };
104
17016
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
7
3170
by: Sam | last post by:
Hello I have a structure called Company. struct Company { char *employee; char *employee_address; }; I want to build an array of this structure but the number of employees will change thorughout the course the programs use so it will need to
12
3888
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...
11
3787
by: skumar434 | last post by:
Hi everybody, I am faceing problem while assigning the memory dynamically to a array of structures . Suppose I have a structure typedef struct hom_id{ int32_t nod_de; int32_t hom_id;
17
2328
by: Ben Bacarisse | last post by:
candide <toto@free.frwrites: These two statements are very different. The first one is just wrong and I am pretty sure you did not mean to suggest that. There is no object in C that is the same as its address. The second one simply depends on a term that is not well-defined. Most people consider the type to be an important part of the notion of
5
3800
by: =?Utf-8?B?QXlrdXQgRXJnaW4=?= | last post by:
Hi Willy, Thank you very much for your work. C++ code doesnot make any serialization. So at runtime C# code gives an serialization error at "msg_file_s sa = (msg_file_s) bf.Deserialize(ms);" I thought that it is very hard to memory map structure array. I need both read and write memory mapped file at both side of C# and C++.
0
9680
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
9528
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
10456
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...
0
10230
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...
0
9052
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...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
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.