basic pointer question
H. S. Teoh
hsteoh at qfbox.info
Fri Jul 11 22:51:40 UTC 2025
On Fri, Jul 11, 2025 at 10:17:02PM +0000, WhatMeWorry via Digitalmars-d-learn wrote:
> ```
> // working function
>
> SDL_Texture* changeTextureAccess(SDL_Texture *texture, SDL_TextureAccess
> newAccess)
> {
> // pertinent code only
> texture = createTexture(renderer, pixelFormat, newAccess, width,
> height);
> return texture;
> }
> ```
>
> The above function is working for me when I call it with:
> ```
> SDL_Texture* sameTexture = changeTextureAccess(sameTexture,
> SDL_TEXTUREACCESS_STREAMING)
> ```
> but I thought a better solution would be simply:
> ```
> void changeTextureAccess(SDL_Texture **texture, SDL_TextureAccess newAccess)
> ```
> Isn't the only way to update a function parameter is by making it a pointer?
> So I thought something like
> ```
> *texture = createTexture(renderer, pixelFormat, newAccess, width, height);
> ```
> would work but that just leads to a whole bunch of other lines of code
> returning compiler errors. Am I at least on the right track here? I've
> been throwing lots of * and & all around and not getting anywhere?
[...]
What exactly are the errors you're getting?
By changing the pointer type, you have to update every place that calls
this function so that they pass the address to their pointer rather than
the pointer they were originally passing.
If you don't want to have to rewrite every caller, and only want to
update the pointers inside the function, use `ref`:
```
void changeTextureAccess(ref SDL_Texture *texture, SDL_TextureAccess newAccess)
```
This way, the pointer type doesn't change and the callers don't have to
be updated in most cases. They may still need to be updated if they
were passing rvalues, since ref cannot bind to rvalues. In that case
you'll have to make a copy of the rvalue, or refactor the code to pass
an lvalue instead.
T
--
Heads I win, tails you lose.
More information about the Digitalmars-d-learn
mailing list