Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing double pointer as function argument

Tags:

c

pointers

I simply want to assign a pointer to another pointer via the function (same memory address). My code is below:

#include <stdio.h>

void d(int** a)
{
    int* val_ptr = malloc(1);
    *val_ptr   = 5;
    printf("%d\n", *val_ptr);

    a = &val_ptr;
}

int main()
{
    int* a = NULL;
    d(&a);
    printf("%d\n", *a);
    return 0;
}

Output from Link

5
Segmentation fault

1 Answers

Your code has three problems:

  1. Here int* val_ptr = malloc(1);, you allocate 1 byte rather than allocating space for an int. Use the following to fix it:

    int* val_ptr = malloc(1 * sizeof(int));
    
  2. This a = &val_ptr; is not what you want. It changes the local pointer and makes it point to the address of val_ptr. This will not affect the pointer that you've defined in main.

    Fix it using

    *a = val_ptr;
    

    This way, the pointer in main will also reflect the change and will point to the malloced memory

  3. You should free the allocated memory after its use. Add

    free(a);
    

    after the printf in main to free it.

like image 186
Spikatrix Avatar answered Apr 10 '26 22:04

Spikatrix