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.

Recommended Answers

All 2 Replies

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.