trilobite
March 9th, 2010, 08:33 AM
Hi all -
I've got the following C code which tries to create a very simple C equivalent of a Python dictionary (with keys and values).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Define the array size */
#define arrsize 5
/* Our "dictionary" consists of an array of structs */
typedef struct dict {
char *key;
char *data;
}arr[arrsize] ;
/* Do a function to insert values into the dict. */
dict insert(char *key, char *data) {
arr[x].key = key;
arr[x].data = data;
return dict;
}
/* Find data in the dict, given a key */
char find(char *key) {
if arr.key == NULL {
printf("Error: key not found");
}
else {
return arr.data;
}
}
/* Main */
int main(void)
{
/* Store some data */
insert("foo", "123");
insert("bar", "456");
insert("baz", "789");
/* Find some data */
find("bar");
return 0;
}
What I'm having problems with is understanding how to make the "insert" function insert the data into the next available element in the array (and to give an error if no more are available). That's why I've got arr.[x]'s in the above code.
I think the code is pretty much on the right track, but if someone can just help to get the above functions working, that would be great!
Many thanks in advance -
- trilobite
I've got the following C code which tries to create a very simple C equivalent of a Python dictionary (with keys and values).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Define the array size */
#define arrsize 5
/* Our "dictionary" consists of an array of structs */
typedef struct dict {
char *key;
char *data;
}arr[arrsize] ;
/* Do a function to insert values into the dict. */
dict insert(char *key, char *data) {
arr[x].key = key;
arr[x].data = data;
return dict;
}
/* Find data in the dict, given a key */
char find(char *key) {
if arr.key == NULL {
printf("Error: key not found");
}
else {
return arr.data;
}
}
/* Main */
int main(void)
{
/* Store some data */
insert("foo", "123");
insert("bar", "456");
insert("baz", "789");
/* Find some data */
find("bar");
return 0;
}
What I'm having problems with is understanding how to make the "insert" function insert the data into the next available element in the array (and to give an error if no more are available). That's why I've got arr.[x]'s in the above code.
I think the code is pretty much on the right track, but if someone can just help to get the above functions working, that would be great!
Many thanks in advance -
- trilobite