0

I am trying to copy strings from a field in one struct to another struct (a node), so that I can ultimately create a hashtable. However, I seem to be having some issues in the actual string copying. I've created a for loop to iterate over the strings in the source stuct, and I know the iteration is working fine, because if I printf the source strings (data[i].c_name), they print out fine. Unfortunately, when I try to printf the destination (class_id), it seems to be empty (and thus of course my hash function isn't doing much). Any insights into the potential problem here would be greatly appreciated. Please let me know if I haven't given enough context.

#define LENGTH 30
#define MAX_OBS 80000

typedef struct
{
    char c_name[LENGTH];
    char s_name[LENGTH];
    double value[MAX_OBS];
}
sample;

typedef struct node
{
    char class_id[LENGTH];
    struct node *next;
}
node;

{
    char class_id[LENGTH];

    for (int i = 0; i < total_columns; i++)
    {
        // malloc a new node pointer for each new class label
        node *new_node = malloc(sizeof(node));

        // check that there was sufficient memory
        if (new_node == NULL)
        {
            return 6;
        }

        // copy c_name into node -- failing - class_id is empty
        strcpy(new_node->class_id, data[i].c_name);
        printf("%s\n", class_id);
    }
}
Allie H
  • 121
  • 1
  • 11

1 Answers1

1

Drop the last char class_id[LENGTH]; that you print as it was never initialized. Then switch your printf() to use the actual target of the strcpy.

 strncpy(new_node->class_id, data[i].c_name, LENGTH);
 printf("%.*s\n", LENGTH, new_node->class_id);

I've also put a few LENGTH limits in my code to assure you don't do bad things on bad input without a terminal \0. Never blindly trust your C input unless you generated it in a fail-safe manner.

Disclaimer: desktop inspection changes. Actual debugging is left as an exercise to the student.

Gilbert
  • 3,740
  • 17
  • 19
  • Ah fantastic! Thank you Gilbert! I'm a little confused conceptually though - the new_node is just pointing to the class_id, so why wouldn't printing the class_id work? Also - I definitely can appreciate the importance of making sure only the LENGTH allowed is copied, but since both fields are defined by the same LENGTH, why wouldn't it be safe to leave that off? Thanks again for your help! – Allie H Oct 04 '16 at 01:33
  • @AllieH The local variable called new_node is not pointing to the local variable called class_id. The local variable called new_node is pointing to a node, which has a member also called class_id that is unrelated to the local variable called class_id. – user253751 Oct 04 '16 at 01:39