473,757 Members | 2,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Associative Array in C?

2 New Member
What I am trying to do is implement a associative array to lookup data based on a key in C. This might simple to do in C++ but I'm restricted to use C. The size of the data for the table isn't too large but too large to structure the code as a clean chain of if/else or similar logic. Also, the lookup key values can be large, unpredictable and not well dispersed which doesn't suit itself to a hash table.

OK so my current idea for implementing this is using an array of C structures which gets initialized and contains all the relevant information. The array will be a module global variable used in the C file which needs this functionality. The array definition would look something like the following:

struct ErrorLookupTabl e
{
long DeviceErrorCode ;
char* ErrorString;
};

#define TableSize 6

static struct ErrorLookupTabl e MyTable[ TableSize ] =
{
{ 45, "Not enough memory" },
{ -66, "File I/O error" },
{ -2565, "Device locked" },
{ 32727, "Device not found" },
{ -32727, "Device not found" },
{ 65534, "Unknown device error" }
//... LOTS more
};

So I have implemented some prototype code based on this and it does work to do lookups. But what I was wondering is how portable is this? Is this legal C as defined by the standard to initalize an array of structures in this way? Is this going to work across platforms? I hope you see my dilemma the code appears to work on my system. But I don't know if it's guaranteed to work everywhere and how portable the library functions I'm working on will be because of it?

After defining the structure as above I would do the lookups with code similar to the following:

while ( ( Counter < TableSize ) && ( MatchFound == 0 ) )
{
if ( ErrorCode == MyTable[ Counter ].DeviceErrorCod e )
{
MatchFound = 1;
StringToReturn = MyTable[ Counter ].ErrorString;
}

Counter = Counter + 1;
}

I do have a secondary question as well. If the above works and is portable then I wonder if rather then using "#define TableSize 6" to define the table size if I just wanted it to be calculated dynamically could I do this as well? I'd calculate the table size with something like the following:

TableSize = sizeof( MyTable ) / sizeof( struct ErrorLookupTabl e );

Would this work or code similar to this? I am writing C library functions which need to be portable. That's why I'm wondering if all this is standard C as defined by the standard or not. Thanks. :)
Mar 3 '08 #1
2 3413
gpraghuram
1,275 Recognized Expert Top Contributor
The code you have written is Standard C(ANSI).


Raghuram
Mar 3 '08 #2
weaknessforcats
9,208 Recognized Expert Moderator Expert
TableSize = sizeof( MyTable ) / sizeof( struct ErrorLookupTabl e );
Be careful of this. sizeopf reports the size of the object on the stack.

When MyTable is passed to a function, only the address passes so your sizeof will report the size of the address and not the array.

Personally, I would use a linked list for this.

Avoid static or global variables. See the article inthe C/C++ HowTos on The Case Against Global Variables.
Mar 3 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

11
2545
by: Stefan Richter | last post by:
Hi, I want to create an associative Array with a PHP variable (article ID) as Key and another associative array as it's value. How do I instanciate it, how can I fill it? I want something like this:
27
11205
by: Abdullah Kauchali | last post by:
Hi folks, Can one rely on the order of keys inserted into an associative Javascript array? For example: var o = new Object(); o = "Adam"; o = "Eve";
6
2019
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference between London and the previous element is 25 (40-15), London has a 25% chance of being selected. When I call the function getAssocItem to do this I need to send in 2 arguments. Is there a quick way to get the maximum key value in the associative
4
2690
by: Robert | last post by:
I am curious why some people feel that Javascript doesn't have associative arrays. I got these definitions of associative arrays via goggle: Arrays in which the indices may be numbers or strings, not just sequential integers in a fixed range. www.sunsite.ualberta.ca/Documentation/Gnu/gawk-3.1.0/html_chapter/gawk_20.html (n.) A collection of data (an array) where individual items can be indexed (accessed) by a string, rather than by...
8
7694
by: Derek Basch | last post by:
Is there any way to associate name/value pairs during an array initialization? Like so: sType = "funFilter" filterTypeInfo = ; filterTypeInfo = new Array("type" : sType); I can do it using this: sType = "String"
47
5088
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they are not at all. If you are doing *array", then you have to use only integer values for array index, as it was since ALGOL.
5
37711
by: soup_or_power | last post by:
Hi I have an associative array like this: arr=30; arr=20;arr=40;arr=10; I want the sort function to sort keys in ascending order of the values on the right hand side with the following result: x4,x2,x1,x3 Can anyone please help me write the function? Thank you
7
39848
by: Robert Mark Bram | last post by:
Hi All! How do you get the length of an associative array? var my_cars= new Array() my_cars="Mustang"; my_cars="Station Wagon"; my_cars="SUV"; alert(my_cars.length);
41
4972
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in the hash are alphabetically sorted if the key happens to be alpha numeric. Which I believe makes sense because it allows for fast lookup of a key.
11
2963
by: Bosconian | last post by:
I'm trying to output the contents of an array of associative arrays in JavaScript. I'm looking for an equivalent of foreach in PHP. Example: var games = new Array(); var teams = new Array(); teams = "Lakers";
0
9487
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
10069
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
9904
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
7285
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
6556
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
5168
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...
1
3828
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
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
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.