1

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() {

   insertFirst(1,"Jan");
   insertFirst(2,"March");

   printf("Original List: "); 

   //print list
   printList();
}
1
  • Note link->month[19] = 0; is a good idea to insure null character termination. Consider alternatives that avoid magic numbers. memcpy(link->month, month, sizeof link->month); link->month[sizeof link->month - 1] = 0; or link->month[0] = 0; strncat(link->month, month, sizeof link->month); Commented Oct 3, 2016 at 21:45

2 Answers 2

3

You are printing the pointer ptr->month, not the actual string.
Try: printf("(%d,%s) ",ptr->key,ptr->month); (%s instead of %d).

Sign up to request clarification or add additional context in comments.

Comments

2

Try

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

instead for the "curious output" problem.

1 Comment

gave you best answer since you were first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.