[英]dynamic allocation of array of pointers
以下代碼給出了分段錯誤。 我無法弄清楚為什么。 請參閱..
#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;
}
在使用gdb進行調試時,它說:
Program received signal SIGSEGV, Segmentation fault.
0x0804843f in main () at temp.c:10
*ptr = (int *)malloc(10 * sizeof (*val));
任何有關此事的幫助表示贊賞。
int **ptr;
*ptr = (int *)malloc(10 * sizeof (*val));
第一個語句聲明了一個雙指針。
第二次取消引用指針。 為了能夠取消引用它,指針應該指向一些有效的內存。 因此不會出現seg錯誤。
如果需要為指針數組分配足夠的內存,則需要:
ptr = malloc(sizeof(int *) * 10);
現在ptr
指向一個足以容納10
個int
指針的內存。
現在可以使用ptr[i]
訪問每個本身都是指針的數組元素,其中,
i < 10
#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;
}
看看下面的程序,也許,它有助於更好地理解。
#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;
}
希望這可以幫助.. ;)。
從概念上講,如果你使用** ptr,那么你需要為ptr&* ptr alloacte memory to defrence ** ptr。
但在你的情況下,你只是為* ptr釋放內存,如果你的編譯器足夠智能它的ptr(一個指針位置)的alloacting內存鏈接* ptr,因此它可以鏈接ptr-> ptr-> * ptr.Hence你沒有得到Seg Fault。
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;
}
以上會奏效。 您可以找到差異並了解原因。
您沒有為其分配內存,而是取消引用** ptr的底線。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.