简体   繁体   English

如何使用int指针?

[英]How to use int pointer?

I have two integer pointers that hold the data for the (SDL) screens height and width in pixels. 我有两个整数指针,分别保存(SDL)屏幕的高度和宽度(以像素为单位)的数据。 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. 但是* w* h保持为nullptrs。 Why Is This? 为什么是这样?

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. 在C(以及某种程度上为C ++)中,通常的做法是,如果要编写一个返回多个值的函数,则调用者必须提供一个指向将输出放置到的变量的指针。

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. 请注意,w和h是正常的整数变量。 I am passing the address of these variables to SDL_GetRendererOutputSize (the & operator takes the address of it's argument); 我正在将这些变量的地址传递给SDL_GetRendererOutputSize&运算符采用其参数的地址); 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. 不要忘了咨询该函数的返回值,如果有错误,在这种情况下该值不为零。

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. 好消息是,它将使代码更简单。

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. 它指向您在(int)位置中存储的内容。 So once you enter some integers for the variables 'w' and 'h' they will display when you use pointer. 因此,一旦为变量“ w”和“ h”输入了一些整数,它们就会在使用指针时显示。 Pointer just tells you what is stored in the location you chose to look at. 指针仅告诉您选择查看的位置中存储了什么。 I hope this clears things up for you! 我希望这可以为您解决一切!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM