简体   繁体   中英

Copying a pointer (instead of it's content) using memcpy

I have a program to handle generic linked list. In one case I use it to hold strings. In the function where i add the new node to the list i perform the following (among other stuff..):

void list_append(list *list, void *element)
{

  // create the new node... 
  listNode *node = (listNode *)malloc(sizeof(listNode));
  node->data = malloc(list->elementSize); // NOTE : elementSize is set to be sizeof(char *)
  node->next = NULL;
  memcpy(node->data, element, list->elementSize);   //**

  // rest of the insertion operation....

Now , in the function that calls the list_append function i perform the following:

 int numNames = 5;
 const char *names[] = { "David", "Kevin", "Michael", "Craig", "Jimi" }; //*

 int i;
 list list;
 list_new(&list, sizeof(char *), free_string ,compareString);

 char *name;
 for(i = 0; i < numNames; i++) {
 name = strdup(names[i]);
 list_append(&list, &name);  //****
 }

In addition , I have a "compare method" to compare 2 strings:

int compareString(void *str1,void *str2)
{

return strcmp(*(char **)str1 ,*(char **)str2);
}

If so I have few questions: 1) What is copied in the line where memcpy is in action ( line //** - the pointer or the content ? does it has anything to do with the way the data to copied is stored in the calling function (line //*)? 2) The node of the generic linked list is defined to have : void *data; so why when i use the compare method I have to cast it to (char * )str1 .... would the cast be different if I had copied the string in another manner? Thanks allot (!!) in advance ,Guy.

3)Another thing - if I change the copy action performed by memcpy into :

memcpy(node->data, element, strlen((char *)element) + 1); //**

It works also - is there a difference in the 2 different ways ? if so - what is better ?

1) You're copying the data contained at element, not the pointer. If you want to copy the pointer, you need to pass &element as the second parameter.

2) The compiler doesn't know what is pointed to by void, so you need to cast to its type.

3) If your linked list functions are supposed to be generic, the first implementation is better. Otherwise your functions will only work for strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM