简体   繁体   中英

copying the content of an dynamic array of structs into another dynamic array using memcpy

I want to copy the content of a dynamic array containing 2 structs to another dynamic array of the same size.

I need an exact copy. When I compile, I get these 2 errors at the last line:

invalid use of undefined type 'struct student' & dereferencing pointer to incomplete type

I don't understand these 2 errors.

Here is my code:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct Movie{
    char name [7];
    int price;
    int year;
};

int main(int argc, char ** argv){

     struct Movie m1,m2;
     strcpy(m1.name,"Rambo");
     m1.price=20;
     m1.year=1980;

     strcpy(m2.name,"universal soldier");
     m2.price=30;
     m2.year=1990;

     struct Movie * db= malloc(2*sizeof(struct Movie));
     *db=m1;
     *(db+1)=m2;

     int i;
     for(i=0;i<2;i++){
         printf("%s\n",(*(db+i)).name);
     }

     struct student * db_copy= malloc(2*sizeof(struct Movie));
     memcpy(&db_copy,&db,sizeof(db));
     for(i=0;i<2;i++){
         printf("%s\n",(*(db_copy+i)).name); //here occur the two errors
     }
}   

You need to let the compiler know what struct student is, and that's nowhere in the code.

The errors mean:

  1. invalid use of undefined type 'struct student': You're using an undefined type
  2. dereferencing pointer to incomplete type: You're dereferencing (accessing actual value / structure) of an incomplete type, since the definition of the type is missing.

I guess the real problem though is that you meant to write:

struct Movie * db_copy= malloc(2*sizeof(struct Movie));

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