這個問題在這里已經有了答案: 可以在其范圍之外訪問區域變數的記憶體嗎? (20 個回答) 錯誤:函式回傳區域變數的地址 8 個回答 堆疊和堆是什么以及在哪里? (32 個回答) 16 小時前關閉。
我正在閱讀 C 中的結構,有兩種方法可以定義結構變數(初始化它并為其創建記憶體)。
編輯:我找到了答案。它不起作用的原因是,該game_struct變數在函式退出后立即被銷毀game_create,然后我留下了一個地址,指向記憶體中一個我不再被允許訪問的地方。該malloc版本起作用的原因是它為結構分配了記憶體,并且我將地址的值傳回了。
- 第一種方法是簡單地將它定義為像這樣的普通變數
struct Person {
char name[50];
int age;
float salary;
};
int main() {
struct Person person1, person2;
strcpy(person1.name, "Joey Gladstone");
person1.age = 13;
}
- 第二種方式就是這樣使用
malloc。
struct game * game_create()
{
struct game * game;
game = malloc(sizeof(struct game));
return game;
}
但是當我嘗試在我的游戲中使用第一種方式時,它向我顯示了這個錯誤:
[1] 2640483 分段錯誤(核心轉儲)./game
這是我定義的結構game.h
#ifndef __GAME_H__
#define __GAME_H__
#include <SDL2/SDL.h>
#include <stdbool.h>
// Struct for displaying text on screen
typedef struct {
SDL_Rect rect;
SDL_Texture * texture;
} text;
// Ship orientation
typedef enum {
HORIZONTAL,
VERTICAL
} orientation;
typedef struct {
SDL_Rect rect;
bool is_placed;
orientation orientation;
} ship;
typedef struct {
SDL_Rect rect;
bool is_hit;
} shot;
struct game {
text title;
SDL_Window * window;
SDL_Renderer * renderer;
SDL_Rect player_aim;
shot player_shots[100];
shot opponent_shots[100];
ship player_ships[10];
ship opponent_ships[10];
bool is_running;
int cell_size;
int grid_width;
int grid_height;
int grid_offset_y;
int placing_ship_index;
int player_grid_offset_x;
int opponent_grid_offset_x;
int placed_ships;
int player_hits;
int opponent_hits;
int player_shots_count;
int opponent_shots_count;
bool is_shooting;
};
struct game * game_create();
void game_run(struct game * game);
void game_init(struct game * game);
int game_terminate(struct game * game);
void game_quit(struct game * game);
text game_get_title(struct game * game);
#endif
這就是我嘗試創建結構變數的方式:
#include "include/game.h"
struct game * game_create()
{
struct game game_struct;
return &game_struct;
}
我得到segmentation fault錯誤,我不明白為什么,我認為它應該有效。我究竟做錯了什么?它適用于malloc但不能這樣作業。
uj5u.com熱心網友回復:
在這個函式中:
struct game * game_create()
{
struct game game_struct;
return &game_struct; // wrong!
}
生命周期game_struct在函式作用域結束時結束,因為它是在堆疊上創建的區域變數。當函式回傳時,它會從堆疊中清除。
如果您希望它比函式的生命周期更長,您應該使用malloc上面的示例在堆上創建它。free當你完成它時不要忘記。
請參閱:C 中變數的存盤持續時間。
uj5u.com熱心網友回復:
#include "include/game.h"
struct game * game_create()
{
struct game game_struct;
return &game_struct;
}
game_struct 在 game_create 回傳時作為區域變數釋放;
如果游戲在您的應用程式中作為單例存在。可以使用以下修改
#include "include/game.h"
struct game * game_create()
{
static struct game game_struct;
return &game_struct;
}
/************************/
#include "include/game.h"
static struct game g_game_struct;
struct game * game_create()
{
return &g_game_struct;
}
否則,使用 malloc
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521918.html
標籤:C指针结构
