你得到段錯誤在該行d->b=&key;
請注意,您有沒有分配任何存儲位置的結構變量d
。因此d
包含一些垃圾值,它試圖使用該垃圾地址來解引用指針並獲取組件b
。這裏是你得到段錯誤的地方。要麼靜態分配結構變量,要麼使用malloc
來動態分配它。
int main()
{
struct data *d;
int *ptr;
/* Here you are allocating memory to the
* pointer variable, which will be used to
* point to the structure type data
*/
d = malloc (sizeof (struct data));
int key=10000;
/* Now you can dereference the pointer
* and get any of the components of the
* structure, because 'd' contains a valid
* address.
*/
d->b=&key;
ptr=(int *)d->b;
printf("%d\n",*ptr);
/* Good practice to free the memory location
* you have allocated. Not freeing will lead to
* memory leak in larger applications. After you
* free the memory location denoted by the address
* stored in 'd', you will not be anymore access
* the contents of it.
*/
free (d);
/* d->b; or d->a; is no more possible at this point
* as we have freed the memory pointed by 'd'
*/
}
或者你可以使用:
int main()
{
/* Not a pointer, statically allocated */
struct data d;
int *ptr;
int key=10000;
d.b=&key;
ptr=(int *)d.b;
printf("%d\n",*ptr);
}
所以,它不是void *
到int *
引起段錯誤的類型轉換。它是您使用但未分配/初始化的指針變量的非法內存引用。
你期待d-> b指向什麼? – supercat 2011-06-08 14:22:29
請僅輸入正確的縮進代碼 – 2011-06-08 14:25:50