基于C语言的抽象数据类型列表数组memcpy

基于C语言的抽象数据类型列表数组memcpy,c,C,我目前正在努力理解一系列结构是如何工作的。以下是完整的代码供参考 #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 14 /****************************************************************** * Data Structure Definition

我目前正在努力理解一系列结构是如何工作的。以下是完整的代码供参考

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 14
/******************************************************************
 * Data Structure Definition                                      *
 ******************************************************************/
typedef struct {
  unsigned int prodID;    /*  product ID, uniquely identifies an element */ 
  char prodDesc[50];      /*  product description*/  
  float prodPrice;        /*  product price*/  
  int prodQty;            /* product count or quantity  */
}product, products[SIZE];                 /* product record */

typedef struct cell {
   products item;             /* array of products */
   int prodCtr;           /* number of products in the list */
}*chocoList;              /*  Definition of the ADT List ver 2 */  

typedef enum {
    TRUE, FALSE
}boolean;

/******************************************************************
 * Function Prototypes                                            *
 ******************************************************************/
void initializeList(chocoList *L);             
void populateSortedList(chocoList L);         
void displayList(chocoList L, char * listName);
void displayProduct(product X);                 
int insertSorted(chocoList L, product X);    
product deleteFirstOccurence(chocoList L, float prodPrice);

int main(void) 
{
    chocoList  L;      /* sorted List  */
    product deleted;     /* container for the deleted record */

    /*---------------------------------------------------------------------------------
    * Problem #1 :: Initialize the choco list. Display the products in the list after* 
    * calling populateSortedList().                                                  *
    * printf("\n\n\nProblem #1:: ");                                                 *
    *--------------------------------------------------------------------------------*/
    printf("\n\n\nProblem #1:: ");
    initializeList(&L); 
    populateSortedList(L);
    displayList(L, "Problem 1");

    /*---------------------------------------------------------------------------------
    * Problem #2 :: Delete 1 product from the list by calling deleteFirstOccurence(). * 
    * Display the returned product record by calling displayProduct().               *
    * printf("\n\n\nProblem #2:: ");                                                 *
    *--------------------------------------------------------------------------------*/
    printf("\n\n\nProblem #2:: ");     
    deleted = deleteFirstOccurence(L, 75.50);
    displayProduct(deleted);

    /*---------------------------------------------------------------------------------
    * CHALLENGE :: Redo Problem #s 1 & 2 using either versions 3 or 4                       *
    * Keep in mind the changes when converting the ADT List Versions                 *
    *--------------------------------------------------------------------------------*/

    getch();
    return 0;
}

/****************************************************************************************
 * This function initializes the list for its first use.                                     *
 ****************************************************************************************/
void initializeList(chocoList *L)
{
    *L = (chocoList)malloc(sizeof(struct cell));
    (*L)->prodCtr = 0;
}

/****************************************************************************************
 * This function populates the list by calling insertSorted().                          *
 ****************************************************************************************/
void populateSortedList(chocoList L)
{
    int x, result = 1;

    product data[] = {  {1501, "Hersheys", 100.50, 10},
                                {1502, "Hersheys Almond", 100.50, 15},
                                {1503, "Hersheys Krackel", 100.50, 15},
                                {1701, "Toblerone", 150.75, 20},
                                {1702, "Toblerone Milk", 150.75, 40},
                                {1703, "Toblerone Honey", 150.75, 10},
                                {1550, "Cadbury", 200.00, 30},
                                {1201, "Kitkat", 97.75, 40},
                                {1450, "Ferrero", 150.50, 50},
                                {1601, "Meiji", 75.50, 60},
                                {1301, "Nestle", 124.50, 70},
                                {1525, "Lindt", 175.50, 80},
                                {1545, "Valor", 100.50, 90},
                                {1455, "Tango", 49.50, 100}
                    };
    for(x = 0; x < 10 && result == 1; x++){
        result = insertSorted(L, data[x]);
    }                 
}

/****************************************************************************************
 * This function display the details of all products in the list.                       *
 ****************************************************************************************/            
void displayList(chocoList L, char * listName) 
{
    int x;
    system("CLS");       /* clears the screen before displaying succeeding lines */

    if(L->prodCtr != 0){
        printf("\nElements of the Product List %s:", listName);
        printf("\n\n%-10s%-15s%10s%10s","ID","Description","Price","Quantity");
        printf("\n%-10s%-15s%10s%10s","--","-----------","-----","--------");

        for(x = 0 ; x < L->prodCtr; x++){
            printf("\n%-10d", L->item[x].prodID);
            printf("%-15s", L->item[x].prodDesc);   
            printf("%10.2f", L->item[x].prodPrice);
            printf("%10d", L->item[x].prodQty);     
        }
    }else{
        printf("\n\tChoco list is currently empty!\n");
    }

    printf("\n\n Press any key to continue . . . ");
    getch();
}

/****************************************************************************************
 * This function inserts a product X in an alphabetically sorted list according to its  *
 * product description. It returns a value of 1 for successful insertion. Otherwise, 0. *
 * Use memcpy() in shifting the elements downward to provide space for the new product. *
 ***************************************************************************************/
int insertSorted(chocoList L, product X)
{
    int ctr;
    if(L->prodCtr<14){
        for(ctr=0; ctr<L->prodCtr && strcmp(L->item[ctr].prodDesc, X.prodDesc)<0;ctr++){    }
        memcpy(L->item + ctr + 1, L->item + ctr, sizeof(product) * (L->prodCtr - ctr));
        L->item[ctr] = X;
        L->prodCtr++;
        ctr = 1;
    }
    else{
        ctr = 0;
    }
    return ctr;
}

/****************************************************************************************
 * This function deletes the first occurence of a product given the prodPrice.It returns* 
 * the product record ones it is found. Otherwise, it returns a dummy record containing *
 * "XXX" for string values and 0 for integer and float values.  Use memcpy() in shifting *
 * the elements upward to avoid having empty indices within the array.                       *
 ***************************************************************************************/
product deleteFirstOccurence(chocoList L, float prodPrice)
{
    int ctr;
    product dummy;
    strcpy(dummy.prodDesc , "XXX");
    dummy.prodID = 0;
    dummy.prodPrice = 0;
    dummy.prodQty = 0;
    for(ctr = 0; ctr<L->prodCtr && L->item[ctr].prodPrice != prodPrice; ctr++){ }
    if(ctr!=L->prodCtr){
        dummy = L->item[ctr];
        memcpy(L->item + ctr, L->item + ctr + 1, sizeof(product) * (L->prodCtr - ctr));
        L->prodCtr--;
    }
    return dummy;
}

/****************************************************************************************
 * This function display the details of 1 product.                                       *
 ***************************************************************************************/
void displayProduct(product X)
{
    //system("CLS");       /* clears the screen before displaying succeeding lines */
    printf("\n\nElements of Product %d:", X.prodID);
    printf("\n\n%-10s%-15s%10s%10s","ID","Description","Price","Quantity");
    printf("\n%-10s%-15s%10s%10s","--","-----------","-----","--------");

    printf("\n%-10d", X.prodID);
    printf("%-15s", X.prodDesc);    
    printf("%10.2f", X.prodPrice);
    printf("%10d", X.prodQty);      

    printf("\n\n Press any key to continue . . . ");
    getch();    
}
其次,在这种情况下使用
memcpy
memmove
是否更有效

首先,有人能给我解释一下这句话吗

memcpy(L->item + ctr + 1, L->item + ctr, sizeof(product) * (L->prodCtr - ctr));
只需
memcpy()
函数将
(产品)*(L->prodCtr-ctr)
存在于
(L->item+ctr)
位置的大小
内容复制到下一个位置,即
(L->item+ctr+1)
。意味着相同的内容将被复制到下一个位置,从
(L->item+ctr+1)


解释

memcpy
用于不希望手动将结构中每个成员的值复制到另一个结构的位置,尤其是当成员是嵌套结构和指针时

struct student 
{
unsigned int marks;
unsigned int reg;
};


struct student mazhar, abbas; 
mazhar.reg = 50;
mazhar.marks = 800;

/* First way. Manually Copy value of each member to destination structure */

abbas.reg = mazhar.reg;
abbas.marks = mazhar.marks;

/* Above method is useful when struct members are not too much. 
   But when you have many members of the structure i.e. like nested 
   structures etc. then you can use memcpy function. */ 

memcpy(&abbas, &mazhar, sizeof(struct student));

memcpy
正试图移动阵列的一部分,以便为新项目腾出空间。从视觉上看,它是这样做的:

在哪里

  • 绿色是数组中不需要移动的项
  • 蓝色是需要移动以为新项目腾出空间的项目
  • 白色是数组中未使用的项
  • 黄色是新项目
    X
在本例中,我选择了以下值:

  • L->prodCtr
    最初为6
  • for
    循环将
    ctr
    设置为3
下面是
memcpy
的工作原理。第一个参数(
L->item+ctr+1
)是目标地址,它是移动后第一个蓝色项目的地址。第二个参数
L->item+ctr
是源地址,它是移动前第一个蓝色项目的地址。第三个论点由两部分组成
sizeof(product)
是每个项目的大小(以字节为单位)
(L->prodCtr-ctr)
是需要移动的项目数。将它们相乘,得到要移动的字节数



这就是
memcpy
应该做的。但是,要回答第二个问题,您不能使用
memcpy
来执行此操作。原因是
memcpy
仅当源和目标不重叠时才起作用<另一方面,code>memmove
,即使源和目标确实重叠,也能保证正常工作。因此,这里没有任何选择,您必须使用
memmove

对漂亮的图片进行投票-因此需要更多的图片。;)非常感谢。你不知道你的回答对我有多重要。我已经快要放弃我的课程了。@PaulR谢谢,我以后会添加更多的图片:-)@BoredChinese不客气,祝你在课堂上好运:-)我投票结束这个问题,因为你可以在谷歌上搜索一些教程,或者读一本关于它的书this@stackptr很酷。我已经从用户3386109那里得到了答案。
memcpy(L->item + ctr + 1, L->item + ctr, sizeof(product) * (L->prodCtr - ctr));
struct student 
{
unsigned int marks;
unsigned int reg;
};


struct student mazhar, abbas; 
mazhar.reg = 50;
mazhar.marks = 800;

/* First way. Manually Copy value of each member to destination structure */

abbas.reg = mazhar.reg;
abbas.marks = mazhar.marks;

/* Above method is useful when struct members are not too much. 
   But when you have many members of the structure i.e. like nested 
   structures etc. then you can use memcpy function. */ 

memcpy(&abbas, &mazhar, sizeof(struct student));