动态分配指针数组 [英] 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;
}
在使用gdb进行调试时,显示:
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.
推荐答案
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);
现在 ptr
指向一个足以容纳 10
指向 int
的指针的内存.
现在可以使用 ptr [i]
其中
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
这篇关于动态分配指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!