2016-04-24 63 views
0

給出一個結構:製作結構fiels常量用C

struct not_const { 
    int a; 
    char *b; 
} nc; 

它的工作原理把它澆鑄成not_const一個const版本:

struct const_version { 
    const int a; 
    const char *b; 
}; 
struct const_version *c = (struct const_version *)&nc; 

莫不是任何填充問題? 我聽說過透明聯盟,但我認爲它們僅用於函數參數。

謝謝。

+0

如果你有'const'成員,你需要'const'初始值設定項。 –

+2

'char * b'的const版本是'char * const b',而不是'const char *'。指針應該是const的,而不是指向它的'char'。 – mch

+1

爲什麼你想要這樣的const結構?爲什麼不簡單地使用'const not_const'? – Holt

回答

-1

我不認爲這個常量有一些關於對齊的問題。在二進制級別,這些類型是兼容的。如果你願意,你可以這樣做(這是用C編寫的很多東西的工作原理 - 大量的網絡代碼,sockaddr_in/sockaddr_in6 - 如果你願意,你可以檢查頭文件)。但正如其他人所說,最好有nc const *你的變量/參數,它最終將釋放你嚴格的引用規則違規。

2

類型不一樣,它們不兼容。該代碼違反嚴格別名。

編譯器可以在結構成員之間放入不同數量的填充。

如果你想獲得一個const成員使用原有的結構定義和使用指針爲const:

const struct not_const* c = (const struct not_const*)&nc; 

這條線會導致編譯器錯誤,因爲它應該:

c->a = 123; 
+0

'const char * b;'不違反嚴格別名規則,但是如果'struct const_version'具有'char * const b;'? –

+1

@sunqingyao即使結構定義相同並具有相同的填充,如果它們不具有相同的標記,它們也不兼容。 – 2501

+0

這就是爲什麼我把'char *',但沒有辦法確保結構的所有字段的「不可用性」? –

0

的另一個答案的問題是數據仍然可以通過其他機構修改爲 。

const struct not_const* c = (const struct not_const*)&nc; 
nc->a=some_other_value; // will still change the data. 

一種解決方案是要分配給c一些存儲器和複製nc它到它。

non_const obj1; 
printf("Enter non_const int : "); 
scanf("%d",&obj1.a); 
obj1.b="SomeString"; 

/* Declare a const version */ 
const non_const *obj3; 
/* Allocate the memory */ 
obj3=malloc(sizeof(obj1); 
/* Copy the first object */ 
memcpy(obj3,&obj1,sizeof(obj1)); 
/* You may see a warning: passing argument 1 
* of ‘memcpy’ discards ‘const’ qualifier from pointer target type 
* which can be neglected if i am not mistaken 
*/ 
+0

事實上,對於一個小型學校項目,我正在開發一個插件系統,我不希望插件能夠從主程序中讀取信息,但不能寫入信息,但這些信息隨時都可能發生變化。 –

+0

@NicolasScottoDiPerto:那麼其他答案已經滿足你的需要了 – sjsam