gpt4 book ai didi

c - 当我将指针与结构一起使用时不理解段错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:56 27 4
gpt4 key购买 nike

我一直遇到段错误,我一辈子都弄不明白为什么!我试着发布我可以用代码编写的最简单的例子(你看到的)来试图找出问题,但我被卡住了。任何事情都会有所帮助!!!!

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;
}

最佳答案

您还没有为您的结构分配内存。您需要 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 .

关于c - 当我将指针与结构一起使用时不理解段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26028280/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com