加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的动态内存分配不起作用

发布时间:2020-12-16 10:13:10 所属栏目:百科 来源:网络整理
导读:我正在尝试在C中创建一个需要动态大小的数组的游戏,但是即使相同的代码在我的另一个程序中工作,我的代码也无法运行. 这是我的#includes #include stdio.h#include stdlib.h#include string.h#include "SwinGame.h" //API for graphics,physics etc#include m
我正在尝试在C中创建一个需要动态大小的数组的游戏,但是即使相同的代码在我的另一个程序中工作,我的代码也无法运行.

这是我的#includes

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SwinGame.h" //API for graphics,physics etc
#include <math.h>

以下是我使用的相关结构的typedef:

typedef struct position_data
{
  double x;
  double y;
} position_data;

typedef enum enemy_type_data {CIRCLE,TRIANGLE,SQUARE} enemy_type_data;

typedef struct enemy_data
{
  position_data location;
  enemy_type_data type;
  bitmap bmp;
  double health;
  double speed;
  int path_to;
} enemy_data;

typedef struct enemy_data_array
{
  int size;
  enemy_data *data;
} enemy_data_array;

这是向元素添加元素的函数:

void add_enemy(enemy_data_array *enemies)
{
  enemy_data *new_array;
  enemies->size++;
  new_array = (enemy_data *)realloc(enemies->data,sizeof(enemy_data) * enemies->size);
  if (new_array) //if realloc fails (ie out of memory) it will return null
  {
    enemies->data = new_array;
    // enemies->data[enemies->size - 1] = read_enemy_data();
    printf("Enemy added successfully!n");
  }
  else
  {
    printf("FAILED. Out of Memory!n");
    enemies->size--;
  }
}

这是我在主程序中的函数调用和变量声明:

int main()
{
  path_data my_path[41];
  enemy_data_array enemies;
  enemies.size = 0;
  add_enemy(&enemies);
}

为什么这不起作用?

解决方法

您通过在具有自动存储持续时间的未初始化变量中传递不确定值enemies->数据来调用未定义的行为.在使用add_enemy()之前初始化它.

int main()
{
  path_data my_path[41];
  enemy_data_array enemies;
  enemies.size = 0;
  enemies.data = 0; /* add this line */
  add_enemy(&enemies);
}

0是空指针常量,可以安全地转换为指针NULL.与NULL不同,0将在不包含任何标头的情况下工作.当然你可以使用enemies.data = NULL;包含适当的标题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读