Hi,
I'm a newbie to C programming and currently very confused. We are studying linked lists right now and our assignment is to create a dictionary program variables.c that stores and retrieves name-value pairs.
I have been working on this for hours and I'm not even sure what I have is correct. Could someone please help me? Even if it's just to tell me the I'm on the right track.
Here's what I've written so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "variables.h"
typedef struct Variable
{
double value;
char* name;
struct Variable* next;
struct Variable* prev;
} Variable_t;
void set_variable(const char* name, double value)
{
Variable_t* new_variable_node(const char* name, double value)
{
Variable_t* new_node = malloc(size of(Variable_t));
assert(new_node != NULL);
new_node->next = NULL;
new_node->prev = NULL;
new_node->value = value;
new_node->name = malloc(strlen(name) + 1);
assert(new_node->name != NULL);
strcpy(new_node->name, name);
return new_node;
}
}
double variable_value(const char* name)
{
The files my professor gave are
variables.h
Code:
#define MAX_VARIABLE_LENGTH 15
/* Set the variable with the specified name to the specified value.
* If there is not a variable with that name in the dictionary,
* add one. */
void set_variable (const char* name, double value);
/* Return the value of the variable with the specified name.
* If variable does not exist, add it to the dictionary
* with a default value of 0.0, and return that value. */
double variable_value(const char* name);
/* Display the names and values of all variables in the dictionary. */
void display_variables();
dictionary_test.c
Code:
#include <stdio.h>
#include "variables.h"
void verify (double result, double expected_value)
{
if (result != expected_value)
{
printf ("Incorrect result. Should be %8.4f\n\n", expected_value);
}
}
int main()
{
double result;
printf ("Starting dictionary test\n\n");
set_variable("A1", 1.0);
set_variable("A2", 2.0);
set_variable("A3_3333", 3.3333);
result = variable_value("A1");
printf ("A1 is %8.4f.\n", result);
verify(result, 1.0);
result = variable_value("A2");
printf ("A2 is %8.4f.\n", result);
verify(result, 2.0);
result = variable_value("A3_3333");
printf ("A3_333 is %8.4f\n", result);
verify(result, 3.3333);
set_variable("A long variable", -1.0);
result = variable_value("A long variable");
printf ("A long variable is %8.4f\n", result);
verify(result, -1.0);
result = variable_value("Unset Variable ");
printf ("Unset Variable is %8.4f\n", result);
verify(result, 0.0);
printf ("\n");
printf ("All variables:\n");
display_variables();
printf ("Dictionary test complete\n");
getchar();
return 0;
}
Any help will be GREATLY appreciated.