当我使用带有结构的指针时,不理解seg错误

时间:2014-09-24 23:44:33

标签: c pointers struct segmentation-fault

我不断遇到段错误,我不能为我的生活找出原因!我试着发布一个最简单的例子,我可以用代码(你看到的)写出来试图找出问题,但我被卡住了。什么都有帮助!!!!

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 个答案:

答案 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中看到的那样。