Allie H Allie H - 2 months ago 6
C Question

C - Problems copying string from one struct to a node

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);
}
}

Answer

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.

Comments