Why in this case should I pass a pointer to a pointer

This question is based on a previous question from me.

There I had this design. It uses SDL2:

void init_window(SDL_Window *window)
{
    window = SDL_CreateWindow(…);
}

int main(void)
{ 
    SDL_Window  *window;
    init_window(window);
}

This did not work. The answer was suggested, I used it *&windowas a function parameter, and it worked perfectly. I copied *&windowin **windowthe following manner:

void init_window(SDL_Window **window)
{
    *window = SDL_CreateWindow(…);
}

int main(void)
{ 
    SDL_Window  *window;
    init_window(&window);
}

And it also works. But I still do not understand why the first version does not work. I looked at the SDL_Window implementation details , and this is just a normal typedefstructure that puts it in a regular namespace. SDL_CreateWindow returns SDL_Surface *.

To present my dilemma, I wrote this simple program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person
{
    char *name;
    int age;
} Person;

Person *person_create(char *name, int age)
{
    Person *who = malloc(sizeof(Person));
    who->name   = strdup(name);
    who->age    = age;

    return who;
}

void person_get_old(Person *who)
{
    who->age += 30;
}

int main(void)
{
    Person *susan = person_create("Susan", 23);
    person_get_old(susan);
    printf("%i\n", susan->age);
}

53 , , . SDL2. SDL2, , , - SDL2, , , . , - .

+4
2

, :

void foo(int p) //create new copy of int
{
    p = 0; //modify copy, original is unchanged
}
void bar(int* p) //create new copy of pointer
{
    *p = 0; //modify object pointer is set to
}

SDL foo. . , .

Person bar. , , . - ( ).

, , ( ). , .

+3

SDL2 , , .

SDL2 , , , . , , .

+3

Source: https://habr.com/ru/post/1629744/


All Articles