來提取res中指向的內存地址內的值。C中使用void指針作爲一種通用指針。一個void指針變量可以用來包含任何變量類型的地址。 void指針的問題是一旦給指針指定了一個地址,關於變量類型的信息就不再可供編譯器檢查。
通常,應該避免使用void指針,因爲其地址在void指針中的變量的類型不再可供編譯器使用。另一方面,有些情況下void指針非常方便。然而,程序員應該知道地址在void指針變量中的變量的類型並正確使用它。
很多舊的C源代碼在類型指針和空指針之間都有C風格轉換。現代編譯器沒有必要這樣做,應該避免。
void指針變量的大小是已知的。未知的是其指針在void指針變量中的變量的大小。例如這裏有一些源代碼示例。
該空指針已被用於
// create several different kinds of variables
int iValue;
char aszString[6];
float fValue;
int *pIvalue = &iValue;
void *pVoid = 0;
int iSize = sizeof(*pIvalue); // get size of what int pointer points to, an int
int vSize = sizeof(*pVoid); // compile error, size of what void pointer points to is unknown
int vSizeVar = sizeof(pVoid); // compiles fine size of void pointer is known
pVoid = &iValue; // put the address of iValue into the void pointer variable
pVoid = &aszString[0]; // put the address of char string into the void pointer variable
pVoid = &fValue; // put the address of float into the void pointer variable
pIvalue = &fValue; // compiler error, address of float into int pointer not allowed
一種方式是通過具有幾種不同類型的被設置爲用於一個函數的參數,典型地某種調度功能的結構的。由於該函數的接口允許使用不同的指針類型,因此必須在參數列表中使用void指針。然後,指向的變量類型由附加參數或檢查指向的變量來確定。這種類型的功能使用的例子將如下所示。在這種情況下,我們在結構的各種排列的第一個成員中包含一個結構類型的指示符。只要所有與此函數一起使用的結構都具有指示結構類型的int
作爲它們的第一個成員,這將起作用。
struct struct_1 {
int iClass; // struct type indicator. must always be first member of struct
int iValue;
};
struct struct_2 {
int iClass; // struct type indicator. must always be first member of struct
float fValue;
};
void func2 (void *pStruct)
{
struct struct_1 *pStruct_1 = pStruct;
struct struct_2 *pStruct_2 = pStruct;
switch (pStruct_1->iClass) // this works because a struct is a kind of template or pattern for a memory location
{
case 1:
// do things with pStruct_1
break;
case 2:
// do things with pStruct_2
break;
default:
break;
}
}
void xfunc (void)
{
struct struct_1 myStruct_1 = {1, 37};
struct struct_2 myStruct_2 = {2, 755.37f};
func2 (&myStruct_1);
func2 (&myStruct_2);
}
喜歡的東西上面有許多的軟件設計問題的耦合和凝聚力所以,除非你有使用這種方法很好的理由,最好是重新考慮你的設計。然而,C編程語言允許你這樣做。
有些情況下void指針是必需的。例如,分配內存的malloc()
函數將返回一個包含已分配區域地址的空指針(如果分配失敗,則返回NULL)。在這種情況下,void指針允許使用一個malloc()
函數,該函數可以返回任何類型變量的內存地址。以下顯示使用各種變量類型的malloc()
。
void yfunc (void)
{
int *pIvalue = malloc(sizeof(int));
char *paszStr = malloc(sizeof(char)*32);
struct struct_1 *pStruct_1 = malloc (sizeof(*pStruct_1));
struct struct_2 *pStruct_2Array = malloc (sizeof(*pStruct_2Array)*21);
pStruct_1->iClass = 1; pStruct_1->iValue = 23;
func2(pStruct_1); // pStruct_1 is already a pointer so address of is not used
{
int i;
for (i = 0; i < 21; i++) {
pStruct_2Array[i].iClass = 2;
pStruct_2Array[i].fValue = 123.33f;
func2 (&pStruct_2Array[i]); // address of particular array element. could also use func2 (pStruct_2Array + i)
}
}
free(pStruct_1);
free(pStruct_2Array); // free the entire array which was allocated with single malloc()
free(pIvalue);
free(paszStr);
}
printf你在說什麼? – Mansuro
你期望什麼樣的價值觀,你究竟得到了什麼? –
它似乎工作[這裏](http://www.ideone.com/P1UEB)指出什麼是不尋常的,它可能會讓你更好的幫助。 –