Dynamic allocation of an array of pointers

The following code gives a segmentation error. I can’t understand why. Please look..

#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; } 

when 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 on this is welcome.

+4
source share
5 answers
 int **ptr; *ptr = (int *)malloc(10 * sizeof (*val)); 

The first statement declares a double pointer.
The second markup of the pointer. So that you can dereference it, the pointer must point to some valid memory. this does not mean segregation.

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

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

Now ptr points to a memory large enough to hold pointers 10 to int .
Now each element of the array, which is a pointer, can be obtained using ptr[i] , where

 i < 10 
+8
source
 #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; } 
+3
source

See the program below, it may help to better understand.

 #include<stdio.h> #include <stdlib.h> int main(){ /* Single Dimention */ int *sdimen,i; sdimen = malloc ( 10 * sizeof (int)); /* Access elements like single diminution. */ sdimen[0] = 10; sdimen[1] = 20; printf ("\n.. %d... %d ", sdimen[0], sdimen[1]); /* Two dimention ie: **Array of pointers.** */ int **twodimen; twodimen = malloc ( sizeof ( int *) * 10); for (i=0; i<10; i++) { twodimen[i] = malloc (sizeof(int) * 5); } /* Access array of pointers */ twodimen[0][0] = 10; twodimen[0][3] = 30; twodimen[2][3] = 50; printf ("\n %d ... %d.... %d ", twodimen[0][0], twodimen[0][3], twodimen[2][3]); return 0; } 

Hope this helps ...;).

+1
source

Conceptually, if you use ** ptr, you need alloacte memory for ptr and * ptr for defrence ** ptr.

But in your case, you only use memory for * ptr, if your compiler is smart enough for alloacting memory for ptr (one pointer location) to bind * ptr, therefore, it could bind ptr-> ptr β†’ * ptr.Hence, you don't get Seg Fault.

0
source

turn on

turn on

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

It would be higher to work. You can find the difference and understand the reason.

In the bottom line, you refused the ** ptr link without allocating memory for it.

0
source

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


All Articles