2014-09-24 80 views
2

我一直在收到seg故障,但我不能爲了我的生活找出原因!我嘗試發佈一些最簡單的例子,我可以用代碼(你看到的)寫出來試圖找出問題,但我被卡住了。任何事情都會有所幫助!當我使用帶指針的指針時,不能理解seg故障

int main() 
{ 
    int i1, i2; 
    struct intPtrs 
    { 
     int *p1; 
     int *p2; 
    }; 

    struct intPtrs *myIntPtr; 

    i1 = 100; 
    i2 = 200; 

    myIntPtr->p1 = &i1; 
    myIntPtr->p1 = &i2; 

    printf("\ni1 = %i, i2 = %i\n",myIntPtr->p1,myIntPtr->p2); 

    return 0; 
} 

回答

1

您還沒有爲您的結構分配內存。你需要malloc(別忘了免費)。

所以,你的代碼應該是這樣的(還有其他的問題,檢查我的代碼):

#include <stdio.h> // printf() 
#include <stdlib.h> // malloc() 

// declare the struct outside main() 
struct intPtrs { 
    int *p1; 
    int *p2; 
}; 

// typedef the struct, just for less typing 
// afterwards. Notice that I use the extension 
// _t, in order to let the reader know that 
// this is a typedef 
typedef struct intPtrs intPtrs_t; 

int main() { 
    int i1, i2; 

    // declare a pointer for my struct 
    // and allocate memory for it 
    intPtrs_t *myIntPtr = malloc(sizeof(intPtrs_t)); 

    // check if allocation is OK 
    if (!myIntPtr) { 
    printf("Error allocating memory\n"); 
    return -1; 
    } 

    i1 = 100; 
    i2 = 200; 

    myIntPtr->p1 = &i1; 
    myIntPtr->p2 = &i2; // here you had p1 

    // you want to print the numbers, thus you need what the p1 and p2 
    // pointers point to, thus the asterisk before the opening parenthesis 
    printf("\ni1 = %d, i2 = %d\n", *(myIntPtr->p1), *(myIntPtr->p2)); 

    // DON'T FORGET TO FREE THE DYNAMICALLY 
    // ALLOCATED MEMORY 
    free(myIntPtr); 

    return 0; 
} 

當我使用結構,我也用一個typedef,你可以在我的例子here看到。

+1

+1另外聲明結構變量而不是指針,並使用'.'(點)運算符代替。如果程序即將退出,那麼「免費」並不是真的需要,但無論如何,記住它是一個很好的實踐。 – 2014-09-24 23:51:06

+0

修復它,非常感謝。所以如果我沒有使用struct的指針,我不應該使用malloc,對吧? – like9orphanz 2014-09-25 00:13:48

+1

正確。你不需要動態分配內存。很好的問題,但這是我的+1。 :) @ like9orphanz – gsamaras 2014-09-25 00:17:13