簡體   English   中英

使用memcpy將結構的動態數組的內容復制到另一個動態數組中

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

我想將包含2個結構的動態數組的內容復制到另一個相同大小的動態數組。

我需要一個精確的副本。 編譯時,在最后一行得到以下兩個錯誤:

無效使用未定義類型'struct student'取消引用不完整類型的指針

我不明白這兩個錯誤。

這是我的代碼:

#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
     }
}   

您需要讓編譯器知道struct student是什么,而這在代碼中就不存在。

錯誤的意思是:

  1. 無效使用未定義類型'struct student':您正在使用未定義類型
  2. 取消引用不完整類型的指針:您正在取消引用(訪問實際值/結構)不完整類型,因為缺少類型定義。

我想真正的問題是您打算寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM