C++指针参数问题

标签 c++ pointers parameters

我是一名初级程序员,使用 SDL 编写图形游戏。将 tile-sheet 拆分为多个部分或“剪辑”并将其放入数组的功能以及将特定“剪辑”绘制到屏幕上的功能未按预期工作。

void split_tilesheet(int width, int height, int space, Entity * ent){
    std::cout << "Splitting Tileset...";

    int t_width = (width / SPR_W);
    int t_height = (height / SPR_H);
    int numTiles = (t_width * t_height);

    ent = new Entity [numTiles + 1];
    if( ent == NULL){
        err("!failed to alloc!");
    }else{
        std::cout << "allocated"<< std::endl;
    }
    int count = 0;
    for(int i = 0; i < t_width; i++){
        for(int j = 0; j < t_height; j++){

            ent[count].bounds.x =  i * SPR_W;
            ent[count].bounds.y = j * SPR_H;
            ent[count].bounds.w = SPR_W;
            ent[count].bounds.h = SPR_H;
            ent[count].id = ent[i].x + ( ent[i].y * t_width);
            count++;
        }
    }
}

void draw_room(char tiledata[MAP_MAX_X][MAP_MAX_Y], Entity * ent){
SDL_Rect bounds;
    for(int x  = 0; x < MAP_MAX_X; x++){
        for(int y = 0; y < MAP_MAX_Y; y++){

            if(tiledata[x][y] == '0' || tiledata[x][y] == ' ' || tiledata[x][y] == '\n' ){
                draw_img(x * SPR_W , y * SPR_H, tiles, bounds, ent[0].bounds); 
            }
            if(tiledata[x][y] == '1'){
                draw_img(x * SPR_W , y * SPR_H, tiles, bounds, ent[1].bounds);
            }
        }           
    }
}

class Entity
{
public:
    SDL_Rect bounds;
    SDL_Surface* sprite;
    int id;
    int x;
    int y;
    int w, h;
 };

我试图使用指针在运行时动态分配内存。 该程序编译,但段错误。 gdb 说段错误是由于 draw_room() 函数引起的,但我不明白为什么。我传递给 draw_room 函数的指针是:

Entity * floor0_clips = NULL;

这个也没用

Entity * floor0_clips;

请帮忙...

最佳答案

C++ 使用按值传递(除非您指定按引用传递),而您没有这样做。

函数中的变量是给定参数的拷贝。例如:

int func(int x)
{
    x = 5;
}

int main()
{
    int y = 6;
    func(y);
    // here, `y` is still `6`
}

您的情况与此基本相同。您将 floor0_clips 发送到一个函数,该函数更新它的一个拷贝,保持原始不变。

要改为使用按引用传递,请将 & 符号放在函数参数列表中的变量名称之前,即在您的情况下 Entity * &ent 。不要更改调用该函数的代码中的任何内容;函数的参数列表声明决定了值是按值传递还是按引用传递。

注意。无论如何,您似乎分配了太多实体(为什么是 + 1?)。

关于C++指针参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24601663/

相关文章:

c++ - vector c++ 的奇怪行为

c++ - 在 C++ 中从 X 毫秒前获取时间戳

c# - 单声道并传递 unicode 字符串

java - 具有通用返回值的方法

javascript - 调用带有绑定(bind)到转发器的参数的 javascript 函数

c++ - 命令提示符打印对话框命令

c - 赋值从整数进行指针转换而没有强制转换,但是有强制转换

c# - 在 C# 中将结构指针作为参数传递

c++ - 本地声明的对象的内部内存在范围外完好无损?

ruby - RSpec stub : Return the parameter