[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Create a associative Array in C

Posted on 2009-02-22
14
Medium Priority
?
2,108 Views
Last Modified: 2012-05-06
Hello

This is my first time ever needing any sort of associative array in C. Reason why i am looking for this is because I am trying to Addapt a flat file program to use MySQL. I just figured for anyone else making changes to it, it would be easier to do so with a associative array then having to keep track of column numbers. especially since some of these tables are going to be over 100 columns in length.

0
Comment
Question by:Pyromanci
  • 6
  • 3
  • 3
  • +1
14 Comments
 
LVL 9

Assisted Solution

by:masheik
masheik earned 60 total points
ID: 23709092
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 1440 total points
ID: 23709579
>>  I just figured for anyone else making changes to it, it would be easier to do so with a associative array then having to keep track of column numbers. especially since some of these tables are going to be over 100 columns in length.

Do you mean you want to map column names to column indexes ? Then an associative array can indeed help you out.

Since it's mapping strings to integers, it won't be very complicated. All you need is :

(a) a hash function that transforms a string into an index for the associative array. This can be as easy as taking the first character of the string, and taking its ASCII value (possibly doing some more processing on it to skip impossible characters).

(b) an array of buckets. A bucket contains all entries of that specific index in the associative array. A bucket can be implemented as a linked list for example, or as a fixed size array, or even one single element.

(c) a collision strategy. Since you want to keep all values, you want a collision strategy that adds the string to the bucket (or to the next bucket).

(d) the necessary functions implementing the operations for the associative array (insert, retrieve, etc.)


Now that's said, maybe you'd consider a different approach : use an enum like below for example :
typedef enum {
  C_COL_NAME_1 = 0,
  C_COL_NAME_2 = 1,
  ...
} Column;
 
/* you can now use C_COL_NAME_1 anywhere that you need the column index (0) */
 
/* For example to show the third column only : */
while ((row = mysql_fetch_row(res))) {
    printf("%s\n", row[C_COL_NAME_3]);
}
 
/* Note of course that instead of C_COL_NAME_x, you choose more useful names like C_ID, C_NAME, C_ADDRESS, etc. */

Open in new window

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23709613
Oh, and masheik : everybody can do a quick Google search and paste the first few results here. But that generally isn't appreciated on this site. It doesn't show that you know what you're talking about, so it doesn't give the asker any confidence that what you say is valid. It also doesn't have a lot of value for the PAQ database (links break).

Please, if you know the answer to a question, take your time to properly write down your response. It will be better for everybody involved.
0
Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
LVL 9

Expert Comment

by:masheik
ID: 23709643
Thanks for the advice infinity08,

i thought it will be somehow help the asker to find a solution.I will take care to answer questions in future
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23709738
Great, that's all one can ask :)
0
 
LVL 24

Expert Comment

by:fridom
ID: 23710228
I do not get the point of your mail Infinity08. The question is:
"because I am trying to Addapt a flat file program to use MySQL"

Ok if I got that right he has a file but likes to put it into database, You'r code queries the database. So either I'm wrong or  you are. For me it seems what  he likes is a way to import flat files into Mysql, and for tha there are extra "READ DATA INFILE" for that.

I can not see how some assiciative array could be of any help for that.

with best regards
Friedrich

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23710516
>> So either I'm wrong or  you are.

My interpretation was that the current version of the application uses a flat file for storing the data. And the next evolution of the application would store the data in a MySQL database.

So, the code that deals with reading/writing from/to a flat file has to be replaced with code reading/writing from/to a MySQL database.

I could be wrong though ... So, let's see what Pyromanci says :)


Re. the associative array bit. The question stated this :

>> it would be easier to do so with a associative array then having to keep track of column numbers.

In other words, rather than referring to a column by its index, he'd like to refer to a column using the name of the column.
An associative array is one way of doing that (mapping column names to column indexes), but the approach I suggested, using enums, seems easier and, and thus preferable.
0
 
LVL 5

Author Comment

by:Pyromanci
ID: 23711296
Well thanks for all the replies.

OK let me go into further detail.The reason i am going from a flat file storage to a MySQL database store is for a web integration and because the program is already Open Source (and i am just making a sub version of the program) I figure it would be easier for people to have to deal with associative arrays over having to have to deal with column numbers.

Ok lets go into a example.

OK, I already know i am going to have a table name sysconfig with 2 columns (Lets say coloumn A and Column B), and lets say in the code this table is called to for read and write 50 times (also this program is currently roughly 500K lines in multiple source files). Now lets say someone in the future needs to alter the table to add a third column (column C) in to meet their needs and places the column after column A. And they only need that third column in 1 of those functions.

So without dealing with a associative array (ie. row["A"], row["B"], row["C"]) the person would then have to find all the references to that table and modify all calls for row[1] to row[2] just to make the change for 1 place.

Ideal i would have a function built into the core code to create this associative array. So that way it can just generate them dynamically based on the results. I know if it were possible i would have to call several mysql api functions and have a few loops.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23711393
As I thought :) You don't really need an associative array. A simple enum would be more than sufficient (and definitely easier). See my first post for an example.
0
 
LVL 5

Author Comment

by:Pyromanci
ID: 23711724
Infinity, problem is with the enum i would have to go through a and define every single column for every single table. right now i am working on the database layout. I am currently at 53 tables each table ranging from 2 columns up to 124 columns. So in my mind doing the enum method is not the best way.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23712042
>> with the enum i would have to go through a and define every single column for every single table

How would that be different from what you have to do with an associative array ?
0
 
LVL 24

Expert Comment

by:fridom
ID: 23713199
For my taste the stuff does not fit very well with. databases. a table does not have two columns sometime, and hundred columns another time. A table is "fixed" insofar as it's really some work  to add columns. So Infinity is IMHO partly right. If you do not like enums just juse an array an index into it. But first you better made up your mind on what your table might look like. And even if he'd now use a flat file he probalby could register it as an ODBC Data source and soe you could  run queris over it. But for me it seem he does not even know when there are how many columns and  how they are named. Howerver one could imageing somethinglike this

struct table_entry {
    size_t line_index;
     char ** rows;
     size_t number_of_rows;
};

so he could read in  the flat file, line by line, he then splits the  line into tokens and keep record on how many are in there. So he easily can access earch record (assuming that each line stands for one "table row"), this could be placed in an array,

But I can not see how you can put such different lines into some database. That's simply not how relational databases work. So maybe he'd better be off with some "persistence layer" for C as e.g BerkeleyDB. Or something else like e.g YAML Format or something which is better suitable for that kind of unstructured data.

But for  a relational  database he has to come up with some sound Database structure....
0
 
LVL 5

Author Comment

by:Pyromanci
ID: 23714930
Ok, the flat files will be gone for good once i complete these changes. I am hand converting the base data into the mysql database as i go through this conversion.

after reading everyone's post i am going to just have to combine some of these ideas. I believe this function should handle my needs.

#include <ctia.h>
 
Array mysql_fetch_assoc (MYSQL_RES result)
{
	unsigned int num_fields;
	unsigned int i;
	MYSQL_FIELD *fields;
	MYSQL_ROW row;
	Array <std::string> assc_row;
	
	row = mysql_fetch_row(result);
	num_fields = mysql_num_fields(result);
	fields = mysql_fetch_fields(result);
	for(i = 0; i < num_fields; i++)
	{
		assc_row[fields[i].name] = row[i];
	}
 
	return assc_row;
}

Open in new window

0
 
LVL 24

Expert Comment

by:fridom
ID: 23731297
The above code will not work as expected. The assignment
assc_row[fields[i].name] = row[i];

Won't work, if I'm not mistaken.

Regards
Friedrich
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
By, Vadim Tkachenko. In this article we’ll look at ClickHouse on its one year anniversary.
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question