473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 #1
20 2282
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?

typedef union {
void *Vptr;
int Int;
short Short;
char Char;
long Long;
long long LLong;
double Double;
long double LDouble;
float Float;
} CELL;

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

struct ARRAY *newArray(size_t siz)
{
// Allocates and returns an ARRAY
// ...
}

int main(void)
{
ARRAY *a;

a = newArray(1024);
a.array[23].Float = 2.13f;
a.array[24].Vptr = malloc(267);
a.array[25].LLong = 533777899LL;
a.array[26].Char = 'F';
a.array[27].Vptr = "This is an example string";
}

I would use a type field to avoid mistakes, storing which
type is stored in tha array by changing:
struct ARRAY {
CELL *array;
char *CellTypes;
size_t size;
};

#define VPTR 1
#define INT 2
#define SHORT 3
.... etc

and you store the type of each cell in the adjacent array of characters.
jacob
Oct 24 '06 #2

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?
You're trying to re-invent the C++ object. If you want to do much of
this, it's best to let the C++ compiler and run-time library worry
about all this.

Some other fields you may want to include: the size of each element, a
code for the type of element, the number of dimensions, maybe a link to
the next object (for garbage collection)

Oct 24 '06 #3
Ancient_Hacker 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?


You're trying to re-invent the C++ object. If you want to do much of
this, it's best to let the C++ compiler and run-time library worry
about all this.
????

See my post above. Why do you need a "C++ object" to do that?

can you explain?

Thanks
Some other fields you may want to include: the size of each element, a
code for the type of element, the number of dimensions, maybe a link to
the next object (for garbage collection)
Oct 24 '06 #4

jacob navia wrote:
See my post above. Why do you need a "C++ object" to do that?

You don't. And you can build your own jet plane with enough Electrolux
vacuum cleaners, aluminum cat food cans, "crazy glue", and duct tape.
But many people find it easier to just go and buy one off the shelf.

It's just that C++ is really good at doing all the error-prone busywork
of creating objects, and it lets you define operators, often overused,
on those objects.

You can do similar things in C, but the results are rarely pretty,
concise, and easy to use.

Not to polish the C++ apple too much, in many ways it's a horrible
design, but it does do a few things a whole lot better than most of us
can cobble up out of odd bits.

Oct 24 '06 #5
Ancient_Hacker posted:
>
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?

You're trying to re-invent the C++ object.

Hmm... I don't see how it's anything like a class object in C++. If anything,
I'd say he's trying to implement the Variant type which exists in Visual
Basic.

--

Frederick Gotham
Oct 24 '06 #6
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.

--
pete
Oct 24 '06 #7
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.
Yes but if you want to store a character, you waste sizeof(void *) bytes
in a pointer to... 1 byte.

Isn't a union (as I indicated in my answer) a better solution?
Oct 25 '06 #8
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?
If you need dynamic typing why are you using C? A dynamically typed
language such as Scheme or Python would be a better choice for such
things.

Regards,
Bart.

Oct 25 '06 #9
Ancient_Hacker wrote:
Not to polish the C++ apple too much, in many ways it's a horrible
design, but it does do a few things a whole lot better than most of us
can cobble up out of odd bits.
But this case is not that much better suited for C++. See my other
reply for better alternatives.

Regards,
Bart.

Oct 25 '06 #10
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,len)\
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.ccwrote in message
news:45********@news.peopletelecom.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.ccwrote in message
news:45********@news.peopletelecom.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_Keith) 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(struct array *arr, size_t pos) {
return !arr || pos>=arr->size ? 0 : arr->data[pos * arr->element_size];
}

void array_set(struct 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(arr, size, element_size)) {
free(arr);
return 0;
}
return arr;
}

struct array *array_init(struct 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(struct 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*jabber.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
Laurent Deniau <la************@cern.chwrites:
Keith Thompson wrote:
>Laurent Deniau <la************@cern.chwrites:
[...]
>>>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?
My apologies. I was referring to the code in the article that started
the thread:

<http://groups.google.com/group/comp.lang.c/msg/9c9c34004ae180b5>

not to the code that you posted later:

<http://groups.google.com/group/comp.lang.c/msg/0b263e52c0850000>

--
Keith Thompson (The_Other_Keith) 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 26 '06 #21

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

Similar topics

14
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...
2
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...
1
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...
4
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...
4
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...
3
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...
94
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...
37
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....
2
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.