简体   繁体   English

使用memcpy复制指针(而不是它的内容)

[英]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: 现在,在调用list_append函数的函数中,执行以下操作:

 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: 另外,我有一个“比较方法”来比较2个字符串:

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; 如果是这样,我几乎没有问题:1)在memcpy行动的行中复制了什么(行// ** - 指针或内容?是否与要复制的数据存储在行中的方式有​​关调用函数(行// *)?2)通用链表的节点定义为: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? 那么为什么当我使用比较方法时,我必须将其转换为(char * )str1 ....如果我以另一种方式复制了字符串,那么转换是否会有所不同? Thanks allot (!!) in advance ,Guy. 谢谢分配(!!),盖伊。

3)Another thing - if I change the copy action performed by memcpy into : 3)另一件事 - 如果我将memcpy执行的复制操作更改为:

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. 1)您正在复制元素中包含的数据,而不是指针。 If you want to copy the pointer, you need to pass &element as the second parameter. 如果要复制指针,则需要将&element作为第二个参数传递。

2) The compiler doesn't know what is pointed to by void, so you need to cast to its type. 2)编译器不知道void指向的是什么,因此需要强制转换为其类型。

3) If your linked list functions are supposed to be generic, the first implementation is better. 3)如果您的链表功能应该是通用的,那么第一个实现更好。 Otherwise your functions will only work for strings. 否则,您的函数只适用于字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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