2316354654 2316354654 - 1 year ago 67
C Question

trying to copy a c string in a struct using only C

I'm trying to insert a hard coded string into a char array value in a struct using only C, so I used memcpy, following the example in another post. But for some reason, I keep getting what looks like an address as output, I'm not sure why.

my console prints out: [ (2,7532592) (1,7524424) ] and other long numbers like that every time. I've checked so many examples on how to copy a sequence of characters into a c string, and it seems like this one was exactly the same. I might just be having trouble understanding pointers. Im not sure why it's spitting out the address value. Can anyone point out what I'm doing wrong? I apologize for any lack of knowledge on my part. My shortened down code is below:

struct node
int key;
char month[20];
struct node *next;

struct node *head = NULL;
struct node *current = NULL;

//display the list
void printList()
struct node *ptr = head;
printf("\n[ ");

//start from the beginning
while(ptr != NULL)
printf("(%d,%d) ",ptr->key,ptr->month);
ptr = ptr->next;

printf(" ]");

//insert link at the first location
void insertFirst(int key, char * month)
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));

link->key = key;

memcpy(link->month, month, 20);
link->month[19] = 0; // ensure termination

//point it to old first node
link->next = head;

//point first to new first node
head = link;

int main() {


printf("Original List: ");

//print list

Answer Source


 printf("(%d,%s) ",ptr->key,ptr->month);

instead for the "curious output" problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download