2011-06-08 42 views
0

我的代碼如下,當在結構中使用一個void *指針到int *指針時發生問題!

#include<stdio.h> 
struct data 
{ 
    int a ; 
    void *b; 
}; 

int main() 
{ 
    struct data *d; 
    int *ptr; 

    int key=10000; 
    d->b=&key; 

    ptr=(int *)d->b; 
    printf("%d\n",*ptr); 
} 

,我得到一個分段錯誤!任何想法爲什麼?在此先感謝您的幫助

+0

你期待d-> b指向什麼? – supercat 2011-06-08 14:22:29

+0

請僅輸入正確的縮進代碼 – 2011-06-08 14:25:50

回答

5

struct data *d只是聲明一個指針。你沒有在任何地方分配這個結構。您需要malloc它或在堆棧或全局聲明它只是struct data d

前者是可以做到這樣的:

d = malloc(sizeof(struct data)); 

如果你選擇後者,訪問b必須被寫爲d.b

3

您沒有爲d分配任何內存。它可能指向一個無效的內存區域,因此 - 分段錯誤。

可以解決這個問題,像這樣:

struct data *d = malloc(sizeof(*d)); 
2

的問題是,你沒有爲d指針分配內存:struct data *d;。這行只會創建一個指針,它不會爲它分配內存。請嘗試以下代碼:

int main() 
{ 
    struct data *d = (struct data*)malloc(sizeof(struct data)); 
    int *ptr; 
    int key=10000; 
    d->b=&key; 
    ptr=(int *)d->b; 
    printf("%d\n",*ptr); 
    free(d); 
} 
+4

不要強制轉換'malloc'的返回值。 – cnicutar 2011-06-08 14:29:25

3

你得到段錯誤在該行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 *引起段錯誤的類型轉換。它是您使用但未分配/初始化的指針變量的非法內存引用。