0

Hello, I'm with difficult in this situation:

void teste(int *p_int)
{      
    printf("&p_int = %li\n", (long int) &p_int);    // Line T1
    printf("p_int = %li\n", (long int) p_int);      // Line T2
    p_int = malloc(sizeof(int));
    (*p_int) = 123;
    printf("*p_int = %li\n", (long int) *p_int);    // Line T3

}

int main(void)
{
    int *m;

    printf("&m = %li\n", (long int) &m);    // Line M1
    printf("m = %li\n", (long int) m);      // Line M2
        
    teste(m);
    
    printf("*m = %i\n", *m);        // Line M3
    free(m);

    
    return 0;
}

When I execute the result is "Segmentation Fault" when reached the "Line M3"

My objetive is pass to m pointer the address of memory allocated by the function teste.
If I do the function return the pointer, all work fine. Is possible make this passing the pointer by argument, like above code?

Thank You.

PS: I'm using gcc on Linux.

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by ricardo.crudo
0

You need to pass a pointer to a pointer for this to work...

Your function should be declared like.

void teste(int **p_int)

and you should pass your pointer like

teste(&m);

The reasoning is simple really. When you pass your pointer to a function it copies the pointer value not the address of the pointer.

Edited by gerard4143: n/a

0

You need to pass a pointer to a pointer for this to work...

Your function should be declared like.

void teste(int **p_int)

and you should pass your pointer like

teste(&m);

The reasoning is simple really. When you pass your pointer to a function it copies the pointer value not the address of the pointer.

Perfect!
Thank You.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.