簡體   English   中英

C中的strcpy不兼容指針類型

[英]Strcpy incompatible pointer type in C

您在下面看到的這段代碼是我的項目的一部分。 編譯此代碼時,出現錯誤。錯誤是“從不兼容的指針類型傳遞'strcpy'的參數1”和預期的'char ',但參數的類型為'char * '。如何解決此問題? 謝謝。

 struct songs
{
    char name[MAX];
    double length;
    struct songs *next;
};
typedef struct songs songs;

struct albums
{
    char title[MAX];
    int year;
    char singerName[MAX];
    songs *bas;
    songs *current;
    struct albums *next;
};
        void add(char albumTitle[],char singerName[], int releaseYear )
    {
        struct albums *temp;
        temp=(struct albums *)malloc(sizeof(struct albums));
        strcpy( temp->title, albumTitle ); /* ERROR */
        temp->year=releaseYear; 
        strcpy( temp->singerName, singerName ); /* ERROR */
        if (head== NULL)
        {
        curr=head=temp;
        head->next=NULL;
        curr->next=NULL;
        }
         else
        {
         curr->next=temp;
         curr=temp;
        }

        printf("Done\n");
    }
char * strcpy ( char * destination, const char * source );

strcpy處理字符串,這些字符串在C中用以null結尾的char數組表示, 該數組的類型為char[]char*

但是,在您的代碼中:

struct albums
{
    char* title[MAX];
    ...
    char* singerName[MAX];
    ...
};

char* []指的陣列char* ,這是指針的陣列,以char 因此albums.titlealbums.singerName不是字符串,而是指針數組。 您應該將其更改為char title[MAX]以具有字符串。

您正在定義指向char的指針數組,而不是chars數組。 使用代替。

char name[MAX];

重要提示,zakinster和SioulSeuguh已回答了您的主要問題

使用strncpy而不是strcpy

strcpy取決於尾隨\\ 0。 如果不存在,則緩沖區溢出有問題。

您聲明了指針數組。 擺脫指針:

struct albums
{
    char title[MAX];
    int year;
    char singerName[MAX];
    songs *bas;
    songs *current;
    struct albums *next;
};

暫無
暫無

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

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