2016-06-29 79 views
-1

我正在嘗試使用結構進行實驗並提出了一個問題當我使用指針將數據分配給結構成員的字符數組時,編譯器將引發錯誤:「賦值給數組類型」。在我的代碼中,我知道一個數組使用靜態內存分配和指針使用malloc進行動態內存分配。有人可以告訴我如何解決這個問題。 Code for passing the structure pointer to a function to print the structure data使用指針將數據分配給結構成員的字符數組

回答

0

在你的榜樣「C」是20個字節數組,所以你可以使用的strcpy:

strcpy(struct_pointer->c, "hellos"); 
-1

請記住,「打着招呼」是不是同一類型的使用char [20],所以你應該試試這個:

strcpy(struct_pointer->c, "hellos"); 

,而不是分配的const char*char[20]可變

0

你的代碼

struct_pointer->c="hellos" 

實際上告訴編譯器做到以下幾點 - 分配內存串"hellos"加空終止和指向此內存分配給struct_pointer->c,這已經是分配的,因此編譯器的抱怨是完全有效的。在C你不能只指定一個字符數組到另一個數組,你需要使用任何類型的存儲複製功能,例如

strcpy(struct_pointer->c, "hellos") 

In my code I know that an array uses static memory allocation and pointer uses malloc for dynamic memory allocation

這不是那樣的,在C你沒有得到自動動態內存分配,除非您明確地調用malloc或其變體。內存"hellos"也分配在堆棧