我的代码如下,
#include<stdio.h>
struct data
{
int a ;
void *b;
};
int main()
{
struct data *d;
int *ptr;
int key=10000;
d->b=&key;
ptr=(int *)d->b;
printf("%d\n",*ptr);
}
我得到了分段错误!!知道为什么??在此先感谢您的任何帮助
答案 0 :(得分:5)
struct data *d
只是声明一个指针。您没有在任何地方分配此结构。您需要malloc
或者在堆栈上或全局声明它struct data d
。
前者可以这样做:
d = malloc(sizeof(struct data));
如果您选择后者,则访问b
必须写为d.b
。
答案 1 :(得分:3)
您没有为d
分配任何内存。它可能指向无效的内存区域,因此 - 分段错误。
你可以这样解决这个问题:
struct data *d = malloc(sizeof(*d));
答案 2 :(得分:3)
您在第d->b=&key;
行遇到分段错误请注意,不已将任何内存位置分配给结构变量d
。所以d
包含一些垃圾值,d->b
它试图使用该垃圾地址取消引用指针并获取组件b
。这是您获得segfault的地方。静态分配struct变量,或使用malloc
动态分配它。
int main()
{
struct data *d;
int *ptr;
/* Here you are allocating memory to the
* pointer variable, which will be used to
* point to the structure type data
*/
d = malloc (sizeof (struct data));
int key=10000;
/* Now you can dereference the pointer
* and get any of the components of the
* structure, because 'd' contains a valid
* address.
*/
d->b=&key;
ptr=(int *)d->b;
printf("%d\n",*ptr);
/* Good practice to free the memory location
* you have allocated. Not freeing will lead to
* memory leak in larger applications. After you
* free the memory location denoted by the address
* stored in 'd', you will not be anymore access
* the contents of it.
*/
free (d);
/* d->b; or d->a; is no more possible at this point
* as we have freed the memory pointed by 'd'
*/
}
或者您可以使用:
int main()
{
/* Not a pointer, statically allocated */
struct data d;
int *ptr;
int key=10000;
d.b=&key;
ptr=(int *)d.b;
printf("%d\n",*ptr);
}
因此,void *
到int *
的类型转换不会导致段错误。它是您已使用但未分配/初始化的指针变量的非法内存引用。
答案 3 :(得分:2)
问题是你没有为d指针分配内存:struct data *d;
。这行只创建一个指针,它不为它分配内存。请尝试以下代码:
int main()
{
struct data *d = (struct data*)malloc(sizeof(struct data));
int *ptr;
int key=10000;
d->b=&key;
ptr=(int *)d->b;
printf("%d\n",*ptr);
free(d);
}