【发布时间】:2021-12-28 16:26:59
【问题描述】:
我想将值添加到我的.数组
typedef struct teleporter {
int start;
int end;
}teleporters;
int main(int argc, char **argv) {
int lenght = 2;
teleporters *teleportPlaces;
teleporters mytele;
mytele.start = 0;
mytele.end = 0;
teleportPlaces = calloc(2, sizeof(teleporters));//malloc (sizeof(teleporters) * (lenght));
if (teleportPlaces != NULL) {
teleportPlaces = NULL;
}
for (int i = 0; i < lenght; i++) {
teleportPlaces[i] = mytele;
}
printf("Teleport END[0] = %d",teleportPlaces[0].end);
free(teleportPlaces);
return 0;
}
但每次我添加它时,都会出现分段错误,
我该如何解决这个错误?如果有关于它的文章或答案,那就太好了,谢谢
【问题讨论】:
-
calloc(2, sizeof(teleporters)*lenght);
-
if (teleportPlaces != NULL) { teleportPlaces = NULL; }- 这是什么? -
@kofemann
2是长度。 -
呵呵
if (teleportPlaces != NULL) { -
请解释一下你对calloc和printf之间所有行的理解。他们真的需要一些解释。或者,如果您通过显式代码保证为 NULL 的指针访问,请解释为什么您对段错误感到惊讶。
标签: c for-loop if-statement dynamic-memory-allocation null-pointer