2016-09-29 108 views
-3

我想用指針修改結構數組的每個元素。用指針修改結構數組

我使用兩種不同大小的數組

struct color 
{ 

    char red; 
    char blue; 
    int white; 
}; 

struct colorInit 
{ 

    char red; 
    char blue; 
    int white; 
    int padding[60]; 
}; 


struct color batch1[30]; 

struct colorInit batchInitializd[30]; 

void modifystruct (struct color *ptr) 

{ 

    for (int i = 0; i < 30; i++) 

    { 

    ptr[i].red = batchInitializd[i].red; 

    ptr[i].white = batchInitializd[i].white; 

    ptr[i].blue = batchInitializd[i].blue; 

} 

} 

我在函數指針使用正確的方式?

+0

我們沒有 「檢查我的代碼」 的網站。如果您有**特定**問題,請提供[mcve]和所有必需的信息。見[問]。 – Olaf

回答

0

我在函數中使用指針的方式嗎?

從句法上來說,是的。

如果ptr指向一個包含30個或更多對象的數組,該函數將正常工作。否則,它將會有未定義的行爲。

由於OP更改了對象類型batchInitializd,以下內容不再有效。

可以簡化功能:

void modifystruct(struct color *ptr) 
{ 
    for (int i = 0; i < 30; i++) 
    { 
     ptr[i] = batchInitializd[i]; 
    } 
} 

+0

請檢查密碼,並讓我知道 – Damodaran

+0

@Damodaran,那也沒關係。 –

+0

......................謝謝Sahu – Damodaran