473,778 Members | 1,958 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically malloc'd array of structs

What would be the correct syntax for setting up
a dynamic array of structs?

Suppose you have a struct declared:

struct relation {
FILE * binFile;
unsigned int numAttrs;
struct attrList * relAttrs; /* definition shown at end of post */
};
typedef struct relation relHeader;

The array only has to be sized once. The size is read from a text
file.

Currently I have something like this:

#include <stdio.h>
int main(void){

unsigned int relCount = 2;
relHeader Headers[relCount-1];

return 0;
}

I would prefer to be able to define Headers as:
relHeader * Headers;

And then malloc space for whatever size I need.
When I try:

Headers = malloc(sizeof(* Headers) * (relCount-1))

I get a warning and a syntax error as follows:

p3.c:26: warning: assignment makes pointer from integer without a cast
p3.c:26: syntax error before "Headers"

What I have will work well enough for my purposes. If it's something
simple I'm missing I'd like to fix it.

Regards,
Grant
struct attribute {
struct attribute * next;
unsigned int attrLen;
char type;
char * attrName;
};
typedef struct attribute attrList;

Nov 14 '05 #1
5 2072
Grant Austin <ga*****@foo.fo o.bar.net> wrote in
news:pa******** *************** *****@foo.foo.b ar.net:
I would prefer to be able to define Headers as:
relHeader * Headers;

And then malloc space for whatever size I need.
When I try:

Headers = malloc(sizeof(* Headers) * (relCount-1))

I get a warning and a syntax error as follows:

p3.c:26: warning: assignment makes pointer from integer without a cast
p3.c:26: syntax error before "Headers"


Because there is no prototype for malloc() and functions without
prototypes default to returning an 'int' type. Since Headers is a pointer
this warning is very helpful. This is *precisely* why we don't cast
malloc's return in C. Simply #include <stdlib.h> and the warning will go
away along with the bug you would have had regarding this.
--
- Mark ->
--
Nov 14 '05 #2
On Fri, 05 Mar 2004 16:15:14 GMT, Grant Austin <ga*****@foo.fo o.bar.net>
wrote:
What would be the correct syntax for setting up
a dynamic array of structs?
You're quite close.

Suppose you have a struct declared:

struct relation {
FILE * binFile;
unsigned int numAttrs;
struct attrList * relAttrs; /* definition shown at end of post */
Because attrList is already a typedef for a struct (well, it will be), this
isn't quite right. See my re-organized code below.
};
typedef struct relation relHeader;

The array only has to be sized once. The size is read from a text
file.

Currently I have something like this:

#include <stdio.h>
int main(void){

unsigned int relCount = 2;
Does "2" really mean 2 structs you'll be reading? If so, why are you
subtracting 1 below? Are you possibly confusing "size" with subscripting
expressions?
relHeader Headers[relCount-1];

return 0;
}

I would prefer to be able to define Headers as:
relHeader * Headers;
No prob.

And then malloc space for whatever size I need.
When I try:

Headers = malloc(sizeof(* Headers) * (relCount-1))
If you're malloc-ing relHeader objects, you just need to specify the size
of a relHeader object (see code below). And again, I suspect you don't want
to be subtracting that 1.

I get a warning and a syntax error as follows:

p3.c:26: warning: assignment makes pointer from integer without a cast
p3.c:26: syntax error before "Headers" Looks like you didn't include a required header file. See my code below.
What I have will work well enough for my purposes. If it's something
simple I'm missing I'd like to fix it.

Regards,
Grant
struct attribute {
struct attribute * next;
unsigned int attrLen;
char type;
char * attrName;
};
typedef struct attribute attrList;


Here's the rolled-up version:

#include <stdio.h>
#include <stdlib.h> /* for malloc */

struct attribute {
struct attribute * next;
unsigned int attrLen;
char type;
char * attrName;
};

typedef struct attribute attrList;

struct relation {
FILE * binFile;
unsigned int numAttrs;
/* struct attrList * relAttrs; /* definition shown at end of post */
attrList * relAttrs; /* note: no 'struct' */
};
typedef struct relation relHeader;

int main(void){

unsigned int relCount = 2;

relHeader * Headers;

/* Headers = malloc(sizeof(* Headers) * (relCount-1)) */
Headers = malloc(sizeof(r elHeader) * relCount);
return 0;
}

HTH,
-leor
Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #3

Thanks,

Lesson learned.

-Grant
Nov 14 '05 #4
On Fri, 05 Mar 2004 16:38:37 GMT, Leor Zolman <le**@bdsoft.co m> wrote:

Headers = malloc(sizeof(* Headers) * (relCount-1))


If you're malloc-ing relHeader objects, you just need to specify the size
of a relHeader object (see code below). And again, I suspect you don't want
to be subtracting that 1.


Sorry, I went brain-dead there. For some reason the * before Headers didn't
register to me. I'd usually put a space before that *, anyway...
-leor

Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #5
Sorry, I went brain-dead there.


No worries, I am brain-dead most of the time.

You're right about the -1. I was thinking subscripts.

-g
Nov 14 '05 #6

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

Similar topics

36
7791
by: Bhalchandra Thatte | last post by:
I am allocating a block of memory using malloc. I want to use it to store a "header" structure followed by structs in my application. How to calculate the alignment without making any assumption about the most restrictive type on my machine? Thanks.
7
3127
by: Fabian Wauthier | last post by:
Hi list, I am trying to dynamically grow a 2 dimensional array (Atom ***Screen) of pointers to a struct Atom (i.e. the head of a linked list). I am not sure if this is the right way to do it: /* Allocate 1st dimension */ if((Screen = (Atom ***) malloc(sizeof(Atom **) * Width)) == NULL) perrexit("malloc");
10
2592
by: junky_fellow | last post by:
What is the correct way of dynamically allocating a 2d array ? I am doing it the following way. Is this correct ? #include <stdlib.h> int main(void) { int (*arr)(3); arr = malloc(sizeof(*arr) * 4); /* I want to dynamically allocate
5
2767
by: Bidule | last post by:
Hi, I'm trying to sort structs defined as follows: struct combinationRec { float score; char* name; }; The number of structs and the length of the "name" field are not known
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;
94
4774
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
7
8731
by: Serpent | last post by:
The C-FAQ describes some techniques here: http://c-faq.com/aryptr/dynmuldimary.html I was using something slightly different from the C-FAQ and I was wondering if it was legal. Say I want a two-dimensional array, like this: int x; but I want it dynamically-allocated, and I want expressions that refer
2
11944
by: hal | last post by:
Hi, I'm trying to make an array of pointers to 'TwoCounts' structs, where the size of the array is arraySize. Right now I'm just mallocing enough space for all the pointers to the structs, and mallocing space for the pointer 'countPtr' in each struct, but do I need to do anything else? Thanks. typedef struct TwoCounts { int *countPtr;
8
3218
by: kiser89 | last post by:
I'm having a problem with my array of structs and segmentation faults. I have this struct that represents one line of a source file: struct threeTokens { int lineNumber; char* cmd; char* param; }; line; This is the code that tries to fill the array of structs, which is a global variable called program: program = malloc(numLines * sizeof(line)); while(NULL != fgets(buffer, SIZE, fp)){ tokenPtr = strtok(buffer,"...
0
9629
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
9470
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
10298
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
10127
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
8957
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
6723
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
5500
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2865
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.