473,770 Members | 1,785 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to calculate size of an array of dynaically malloc'd structs?

Hello

If I do this:

struct mystruct
{
long nKey;
char szItem[20];
};

long numitemstocreat e = GetItems();
struct mystruct* devlist = (mystruct*)mall oc(numlines * sizeof(mystruct ));

// Then populate some values

Now I want to find number of array elements - ie get numitemstocreat e. I
know I already have it - but may want to get again.

How do I get the number of array items?

Angus Comber
an***@NOSPAMite loffice.com

Nov 14 '05 #1
4 6401
Angus Comber wrote:
struct mystruct* devlist = (mystruct*)mall oc(numlines * sizeof(mystruct ));

// Then populate some values

Now I want to find number of array elements - ie get numitemstocreat e. I
know I already have it - but may want to get again.


See section 7 of the C FAQ.

Jeremy.
Nov 14 '05 #2
Angus Comber wrote:

Hello

If I do this:

struct mystruct
{
long nKey;
char szItem[20];
};

long numitemstocreat e = GetItems();
struct mystruct* devlist = (mystruct*)mall oc(numlines * sizeof(mystruct ));

// Then populate some values

Now I want to find number of array elements
- ie get numitemstocreat e.
I know I already have it - but may want to get again.


Keep track of it.
Pass it as an argument to every function in the sequence
of calls that leads to the function that actually uses it.

--
pete
Nov 14 '05 #3


Angus Comber wrote:
Hello

If I do this:

struct mystruct
{
long nKey;
char szItem[20];
};

long numitemstocreat e = GetItems();
struct mystruct* devlist = (mystruct*)mall oc(numlines * sizeof(mystruct ));

// Then populate some values

Now I want to find number of array elements - ie get numitemstocreat e. I
know I already have it - but may want to get again.

How do I get the number of array items?


typedef struct mystructArr
{
struct mystruct *element;
size_t size;
}mystructArr;

Declare and use a datatype that has a member that points to the array
and a member that keeps a count of the number of array elements allocate.

Example of use:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ITEMSZ 20

typedef struct mystruct
{
long nKey;
char szItem[ITEMSZ];
}mystruct;

typedef struct mystructArr
{
mystruct *element;
size_t size;
}mystructArr;

mystruct *AddElement(mys tructArr *p,long key, const char *s);
void FreeElements(my structArr *p);

int main(void)
{
mystructArr names = {NULL,0};
size_t i;

AddElement(&nam es,7L,"George Washington");
AddElement(&nam es,45L, "George Bush");

puts("The array contents");
for(i = 0; i < names.size;i++)
printf("names.e lement[%u].szItem = \"%s\"\n"
"names.elem ent[%u].nKey = %ld\n\n",i,
names.element[i].szItem,i, names.element[i].nKey);
FreeElements(&n ames);
return 0;
}

mystruct *AddElement(mys tructArr *p, long key, const char *s)
{
mystruct *tmp;
size_t cnt;

if( !p || ITEMSZ < 1) return NULL;
cnt = p->size;
if((tmp = realloc(p->element,(cnt+1 )*(sizeof *tmp))) == NULL)
return NULL;
p->element = tmp;
p->element[cnt].nKey = key;
strncpy(p->element[cnt].szItem, s, ITEMSZ);
p->element[cnt].szItem[ITEMSZ-1] = '\0';
p->size++;
return &p->element[cnt];
}

void FreeElements(my structArr *p)
{
if(p)
{
free(p->element);
p->element = NULL;
p->size = 0;
}
return;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
Angus Comber wrote:
Hello

If I do this:

struct mystruct
{
long nKey;
char szItem[20];
};

long numitemstocreat e = GetItems();
struct mystruct* devlist = (mystruct*)mall oc(numlines * sizeof(mystruct ));
Doesn't anyone follow the newsgroup or check its FAQs before posting. The
invocation of malloc above is extremely ugly. Just use
struct mystruct *devlist = malloc(numlines * sizeof *devlist);
// Then populate some values
No, that is _not_ what you do next. You check the value of devlist to see
if the malloc failed and, if it failed, handle it.

Now I want to find number of array elements - ie get numitemstocreat e. I
know I already have it - but may want to get again.
Then save it. What idiot wouldn't be able to figure that out? One that
doesn't follow the newsgroup or check the FAQs before posting, that kind of
idiot.

How do I get the number of array items?


You have it. "My feet are on the ground. How do I get my feet on the ground?"

--
Martin Ambuhl
Nov 14 '05 #5

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

Similar topics

2
7672
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray = (data_type**)malloc(widht*height*sizeof(data_type)+ height* sizeof(data_type*)); //allocate individual addresses for row pointers. Now that I am moving to C++,am looking for something by which I can
6
4152
by: Herrcho | last post by:
in K&R Chapter 6.3 it mentions two methods to calculate NKEYS. and points out the first one which is to terminate the list of initializers with a null pointer, then loop along keytab until the end is found is less efficient than using sizeof operator , since size of the array is completely determined at compile time. i don't quite understand this. Could anyone explain to me in detail ?
10
4128
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr; };
22
2465
by: Wynand Winterbach | last post by:
I think every C programmer can relate to the frustrations that malloc allocated arrays bring. In particular, I've always found the fact that the size of an array must be stored separately to be a nightmare. There are of course many solutions, but they all end up forcing you to abandon the array syntax in favour of macros or functions. Now I have two questions - one is historical, and the other practical. 1.) Surely malloc (and...
31
3742
by: bilbothebagginsbab5 AT freenet DOT de | last post by:
Hello, hello. So. I've read what I could find on google(groups) for this, also the faq of comp.lang.c. But still I do not understand why there is not standard method to "(...) query the malloc package to find out how big an allocated block is". ( Question 7.27) Is there somwhere explained why - because it would seem to me, that free()
15
3842
by: Paminu | last post by:
Still having a few problems with malloc and pointers. I have made a struct. Now I would like to make a pointer an array with 4 pointers to this struct. #include <stdlib.h> #include <stdio.h> typedef struct _tnode_t { void *content; struct _tnode_t *kids;
7
1646
by: Jake Thompson | last post by:
Hello I have the following defined structure struct cm8linkstruc { char *type; /* type of item*/ char *desc; /* description of item */ char *item_increment; /* increment value for item in folder */
26
3406
by: Adam Warner | last post by:
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;
33
7185
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d array, so im inputting the dimensions of those myself. The problem is that the output array (C=A*B) has as many rows as A and as many columns as B. I would think of initialising C with:
0
9454
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
10257
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
10099
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
10037
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
9904
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...
0
8931
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
7456
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...
1
4007
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
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.