473,791 Members | 3,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

general array in C

Cyn
Hi,
I want to create a general array structure which can hold all types.
Something like this:

struct ARRAY
{
void **array;
size_t size;
};

Work nice to store pointers to structures in it but what is a good way to be
able to both store pointers to structures and primitive types in it?
Oct 24 '06
20 2327
pete wrote:
Cyn wrote:
>Hi,
I want to create a general array structure which can hold all types.
Something like this:

struct ARRAY
{
void **array;
size_t size;
};

Work nice to store pointers to structures
in it but what is a good way to be
able to both store pointers to structures and primitive types in it?

With a generic list node:
struct list_node {
struct list_node *next;
void *data;
};
you can have lists of any data format.
But if you want to use that list node to store a list of ints, you still
have to store the ints elsewhere and put pointers to them into the list.
That's a waste of memory compared with being able to put the ints
directly into the list_node structure.

Jacob's solution, to use a union of different types, is a good one. But
it would pay to consider what types you actually need to be able to
store. The included types long long, double and long double are all at
least 64 bits and may be even more. The long double on my machine is 96
bits (12 bytes), three times the size of a pointer to void or an int.
That's tripling the size of the 'array'.

--
Simon.
Oct 25 '06 #11

Frederick Gotham wrote:
Hmm... I don't see how it's anything like a class object in C++.
You're right, it is not a simple class object. But if you think it
through, he's going to need ways of operating on gamut of types, and C
doesnt provide much help there, but with C++ operator definitions
there's a way.

Oct 25 '06 #12
Ancient_Hacker posted:
>Hmm... I don't see how it's anything like a class object in C++.

You're right, it is not a simple class object. But if you think it
through, he's going to need ways of operating on gamut of types, and C
doesnt provide much help there, but with C++ operator definitions
there's a way.

Here's what the OP said:

I want to create a general array structure which can hold all types.
Something like this:

struct ARRAY
{
void **array;
size_t size;
};

The question was poor formed, as it does not coincide with the sample
snippet. All the sample snippet does is store a pointer and a length in a
struct!

This is trivial:

struct PtrPlusLenght {
void const *p;
size_t len;
};

Wrapping an array within a struct is a different concept altogether. In
C++, it might be done something like:

template<class T,size_t len>
struct ArrayWrapper {
T arr[len];
};

, while in C, it might be something like:

#define DEFINE_TYPE(T,l en)\
struct ArrayWrapper_## T##_##len {\
T arr[len];
};

(Of course, you'll have problems in C if the type is something like char
(*p)(int) ).

--

Frederick Gotham
Oct 25 '06 #13
Cyn wrote:
Hi,
I want to create a general array structure which can hold all types.
Something like this:

struct ARRAY
{
void **array;
size_t size;
};

Work nice to store pointers to structures in it but what is a good way to be
able to both store pointers to structures and primitive types in it?
see my post on "Extremly fast dynamic array implementation" in this group:

http://groups.google.fr/group/comp.l...263e52c0850000

The code is incomplete but I can provide full source code self-contained
(actually it throws exceptions).

a+, ld.
Oct 25 '06 #14
Cyn

"Simon Biber" <ne**@ralmin.cc wrote in message
news:45******** @news.peopletel ecom.com.au...
Jacob's solution, to use a union of different types, is a good one. But it
would pay to consider what types you actually need to be able to store.
The included types long long, double and long double are all at least 64
bits and may be even more. The long double on my machine is 96 bits (12
bytes), three times the size of a pointer to void or an int. That's
tripling the size of the 'array'.
Yes I like jacob's solution and I already made the same choice to not
include 64 bits types (yet)
For all the people recommending other languages, I work on embedded platform
and C is the language we use. It's not like I can go around and say "hey
lets change language because it fits the problem Im solving better"
Oct 25 '06 #15
Cyn wrote:
"Simon Biber" <ne**@ralmin.cc wrote in message
news:45******** @news.peopletel ecom.com.au...
>>Jacob's solution, to use a union of different types, is a good one. But it
would pay to consider what types you actually need to be able to store.
The included types long long, double and long double are all at least 64
bits and may be even more. The long double on my machine is 96 bits (12
bytes), three times the size of a pointer to void or an int. That's
tripling the size of the 'array'.


Yes I like jacob's solution and I already made the same choice to not
include 64 bits types (yet)
For all the people recommending other languages, I work on embedded platform
and C is the language we use. It's not like I can go around and say "hey
lets change language because it fits the problem Im solving better"
If you are on embedded platform, you probably care about memory usage
and jacob's solution is not optimal (similar to what Perl do). See my
other post.

a+, ld.
Oct 25 '06 #16
Laurent Deniau <la************ @cern.chwrites:
Cyn wrote:
>I want to create a general array structure which can hold all
types. Something like this:
struct ARRAY
{
void **array;
size_t size;
};
Work nice to store pointers to structures in it but what is a good
way to be able to both store pointers to structures and primitive
types in it?

see my post on "Extremly fast dynamic array implementation" in this group:

http://groups.google.fr/group/comp.l...263e52c0850000

The code is incomplete but I can provide full source code
self-contained (actually it throws exceptions).
Be sure to read that entire thread. The posted code is full of
useless casts, it deliberately doesn't check for allocation errors,
and it *isn't C*. (I think it depends on gcc-specific extensions.)

And if your full source code "throws exceptions", it certainly isn't C.

--
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.
Oct 25 '06 #17
"Cyn" <se*@n.tkwrites :
I want to create a general array structure which can hold all types.
Something like this:

struct ARRAY {
void **array;
size_t size;
};

Work nice to store pointers to structures in it but what is a good
way to be able to both store pointers to structures and primitive
types in it?
You've been given some solutions involving unions and pointers but as
it was pointed they waste some memory. You may think of using
something like (it requires C99):

#v+
struct array {
size_t size;
size_t element_size;
char data[];
};

struct array *array_new(size _t size, size_t element_size) {
struct array *arr = malloc(size * element_size + sizeof *arr);
if (!arr) return 0;
arr->size = size;
arr->element_size = element_size;
return arr;
}

struct void *array_get(stru ct array *arr, size_t pos) {
return !arr || pos>=arr->size ? 0 : arr->data[pos * arr->element_size];
}

void array_set(struc t array *arr, size_t pos, void *element) {
if (!arr || pos>=arr->size) return;
memcpy(arr->data + pos * arr->element_size , element, arr->element_size );
}
#v-

or (if using C99 is not an option), use:

#v+
struct array {
size_t size;
size_t element_size;
char *data;
};

struct array *array_new(size _t size, size_t element_size) {
struct array *arr = malloc(sizeof *arr);
if (!array_init(ar r, size, element_size)) {
free(arr);
return 0;
}
return arr;
}

struct array *array_init(str uct array *arr, size_t size,
size_t element_size) {
char *data;
if (!arr || ! (data = malloc(size * element_size))) return 0;
arr->size = size;
arr->element_size = element_size;
arr->data = data;
}

void array_free(stru ct array *arr) {
if (arr) {
free(arr->data);
free(arr);
}
}
#v-

or (another option not requiring array_free()):

#v+
struct array {
size_t size;
size_t element_size;
char *data;
};

struct array *array_new(size _t size, size_t element_size) {
struct array *arr = malloc(size * element_size + sizeof *arr);
if (!arr) return 0;
arr->size = size;
arr->element_size = element_size;
arr->data = arr + 1;
return arr;
}
#v-

I;m not sure if there would be no problems with alignment though.

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >--<jid:mina86*jab ber.org>--ooO--(_)--Ooo--
Oct 26 '06 #18
Keith Thompson wrote:
Laurent Deniau <la************ @cern.chwrites:
>>Cyn wrote:
>>>I want to create a general array structure which can hold all
types. Something like this:
struct ARRAY
{
void **array;
size_t size;
};
Work nice to store pointers to structures in it but what is a good
way to be able to both store pointers to structures and primitive
types in it?

see my post on "Extremly fast dynamic array implementation" in this group:

http://groups.google.fr/group/comp.l...263e52c0850000

The code is incomplete but I can provide full source code
self-contained (actually it throws exceptions).


Be sure to read that entire thread.
I did.
The posted code is full of
useless casts,
Could you show me the useless casts in the posted code? I do not say
that the code is perfect, but I do not see useless casts ((void*) casts
are there for information)
it deliberately doesn't check for allocation errors,
Could you show me what allow you to say that?
and it *isn't C*. (I think it depends on gcc-specific extensions.)
This is pure C89 code (inline vanishes if OOC_ISO_C < OOC_ISO_C99).

May I suggest you to read again the code?
And if your full source code "throws exceptions", it certainly isn't C.
This is pure C89 code, it compiles without warning with the following
gcc 4.1.1 options:

-std=c89 -pedantic -Wall -W -Wstrict-prototypes -Wmissing-prototypes
-Wmissing-declarations -Wchar-subscripts -Wformat-nonliteral
-Wcast-align -Wpointer-arith -Wbad-function-cast -Winline -Wcast-qual
-Wshadow -Wwrite-strings -Wfloat-equal -Wconversion -Wno-conversion
-O3 -fno-ident -floop-optimize2 -fgcse-sm -fgcse-las

But I as said, the posted code is part of a framework which amongst of
other, implements exceptions in C. I can make it free from this
dependance on request which will of course make new and alloc return
NULL instead of throwing an exception, and make get and set will use
assert instead of throwing an exception. This is the price to pay for
standalone code.

a+, ld.
Oct 26 '06 #19
Michal Nazarewicz wrote:
"Cyn" <se*@n.tkwrites :
>>I want to create a general array structure which can hold all types.
#v+
struct array {
size_t size;
size_t element_size;
char *data;
};

struct array *array_new(size _t size, size_t element_size) {
struct array *arr = malloc(size * element_size + sizeof *arr);
if (!arr) return 0;
arr->size = size;
arr->element_size = element_size;
arr->data = arr + 1;
return arr;
}
#v-

I;m not sure if there would be no problems with alignment though.
There will (e.g. you cannot store double in your array). See my post
which does exactly this by providing a type specific interface
("template" code) while implementation is generic but requires hidden
information. This solution is as same access semantic and efficiency as
C arrays (e.g. a[i]), has no problem of alignment, and minimize memory
usage.

a+, ld.
Oct 26 '06 #20

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

Similar topics

14
2656
by: 2mc | last post by:
Generally speaking, if one had a list (from regular Python) and an array (from Numerical Python) that contained the same number of elements, would a While loop or a For loop process them at the same speed? Or, would the array process faster? I'm new to Python, so my question may expose my ignorance. I appreciate anyone's effort to help me understand. Thanks. It is much appreciated.
2
2015
by: Ross Micheals | last post by:
All I have some general .NET questions that I'm looking for some help with. Some of these questions (like the first) are ones that I've seen various conflicting information on, or questions that I'm not sure are specific anomolies that I'm having, or if they are specific known issues I'm facing. 1. In VB.NET, are arrays stored on the stack or the heap? Why must arrays of value types be boxed in order for them to be (effectively) passed by...
1
1806
by: jason | last post by:
Hello everyone, I have some general questions about the DataTable object, and how it works. Moderately new to C#, I have plenty of texts describing the language, but not so much to reference ADO.NET objects (only the MSDN help files). I have written a C# Class Library that is responsible for encapsulating database information. All the objects work just fine for singleton record insert, update, select, and delete operations. But now we...
4
1152
by: Bill | last post by:
In vbscript and vb6 when you created a array via a join that contained no entries when you did a ubound against that array it returned -1, which of course was very helpful for using it as the upper bound in a for loop. In vb.net, in the same situation the ubound will return 0 and you get an array with 1 null entry. I am missing something here or does this seem totally incompatible?
4
3517
by: Saul775 | last post by:
Hello, all: Just a general question that's been bothering me. Suppose I'd like to create a 2D array of integers -- not using the vector template -- but I need to dynamically create the array as I do not know the dimensions. How could I do this using the "new" operator? For instance, suppose I need to create an array of size row x column, but I don't know the values being passed into the function...
3
1541
by: johnmann56 | last post by:
Hello. I have a small C# program which uses a number of large arrays of double. The program runs fine on my desktop PC which has 2 GB of memory, but when run on my laptop with 512 MB the laptop practically freezes up, from running out of memory. I would therefore like to modify my program so that memory space used by the various arrays can be freed up once I am done with each array. I have tried many things before calling GC.Collect(),...
94
4780
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?
37
7181
by: dmoran21 | last post by:
I am a mathematician trying to write a program in C to do some curve fitting. When I get to the point where I attempt to enter data in my arrays, I get a General Protection Exception error message. What is this and how can I fix it. I am writing in Turbo C++. My source code is below. #include <stdio.h> #include <stdlib.h> #include <math.h>
2
3054
by: subhasree | last post by:
Hi, I am a student of mathematics and quite new to programming in C. I am trying to write a code to construct an array which at every step has to compare the value of the current element with all the existing elements in the array. The code is compiling without error. However whenever I try to run it, I get General Protection Exception. Here is my code: #include <stdio.h> #include <conio.h>
0
9515
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
10427
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
10155
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
9029
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
7537
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
5431
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
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
3
2916
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.