ciaran wickham
ciaran wickham

Reputation: 3

How to use int pointer?

I have two integer pointers that hold the data for the (SDL) screens height and width in pixels. They're declared here:

int *w = nullptr;
int *h = nullptr;

Given values here:

    int SDL_GetRendererOutputSize(SDL_Renderer* renderTarget, int *w, int *h);

And used here:

Dest.w = (*w / 2.0f - 58 / 2.0f, *h / 2.0f - 8 / 2.0f);
Dest.h = (*w / 2.0f - 58 / 2.0f, *h / 2.0f - 8 / 2.0f);
Dest.x = (*w / 2.0f - 58 / 2.0f, *h / 2.0f - 8 / 2.0f);
Dest.y = (*w / 2.0f - 58 / 2.0f, *h / 2.0f - 8 / 2.0f);

However *w and *h stay nullptrs. Why Is This?

Upvotes: 0

Views: 1306

Answers (3)

Katie Stevers
Katie Stevers

Reputation: 145

By setting them to zero you are declaring them. It tells the program they will hold an integer(number). Does that make since? Also, a pointer does exactly what it sounds like. It points to what you have stored in the (int)location. So once you enter some integers for the variables 'w' and 'h' they will display when you use pointer. Pointer just tells you what is stored in the location you chose to look at. I hope this clears things up for you!

Upvotes: 0

harmic
harmic

Reputation: 30597

It's common practice in C (and to a certain extent C++) that if you are writing a function that returns multiple values, the caller has to supply a pointer to the variables which the outputs will be placed into.

So, you would call this function like this:

int w=0,h=0;

int result = SDL_GetRendererOutputSize(renderTarget, &w, &h);
if (result!=0) {
    // handle an error here
}

Note that w and h are normal integer variables. I am passing the address of these variables to SDL_GetRendererOutputSize (the & operator takes the address of it's argument); the function presumably sets the variables.

Don't forget to consult the return value of the function, which in this case is non zero if there was an error.

Upvotes: 5

xiaofeng.li
xiaofeng.li

Reputation: 8587

I think what you need to do is to actually allocate two integers for the height and width, then pass the address of them to the function.

int w = 0, h = 0;
// Tell the function where to put the height and width by passing in the address of the two. 
// Assuming renderTarget is in scope.
SDL_GetRendererOutputSize(renderTarget, &w, &h);

Of course, you have to change the code using them. Good news is, it'll make the code simpler.

Upvotes: 0

Related Questions