Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic allocation of array of pointers

The following code gives a segmentation fault. I am not able to figure out as to why. Please see..

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

int main()
{
    int **ptr;
    int *val;
    int x = 7;
    val = &x;
    *ptr = (int *)malloc(10 * sizeof (*val));
    *ptr[0] = *val;
    printf("%d\n", *ptr[0] );

    return 0;
}

on debugging with gdb, it says:

Program received signal SIGSEGV, Segmentation fault.

0x0804843f in main () at temp.c:10

*ptr = (int *)malloc(10 * sizeof (*val));

Any help regarding the matter is appreciated.

like image 575
Vivek Sethi Avatar asked Sep 25 '12 09:09

Vivek Sethi


People also ask

How do you dynamically allocate a pointer array?

To create a variable that will point to a dynamically allocated array, declare it as a pointer to the element type. For example, int* a = NULL; // pointer to an int, intiallly to nothing. A dynamically allocated array is declared as a pointer, and must not use the fixed array size declaration.

Can we dynamically allocate array?

In addition to dynamically allocating single values, we can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime.

How do pointers help in dynamic allocation?

Dynamic memory allocation is to allocate memory at “run time”. Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable).


2 Answers

int **ptr; 
*ptr = (int *)malloc(10 * sizeof (*val));

First statement declares a double pointer.
Second dereferences the pointer. In order that you are able to dereference it the pointer should point to some valid memory. it does not hence the seg fault.

If you need to allocate enough memory for array of pointers you need:

ptr = malloc(sizeof(int *) * 10); 

Now ptr points to a memory big enough to hold 10 pointers to int.
Each of the array elements which itself is a pointer can now be accessed using ptr[i] where,

i < 10
like image 152
Alok Save Avatar answered Sep 18 '22 17:09

Alok Save


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

int main(void)
{
    int **ptr;
    int x;

    x = 5;

    ptr = malloc(sizeof(int *) * 10);
    ptr[0] = &x;
    /* etc */

    printf("%d\n", *ptr[0]);

    free(ptr);
    return 0;
}
like image 36
Kludas Avatar answered Sep 18 '22 17:09

Kludas