[英]Problem when typecasting a void * pointer used inside a structure to an int * pointer!
我的代码如下,
#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);
}
我得到一个分段错误? 知道为什么吗? 提前感谢您的帮助
struct data *d
仅仅声明了一个指针。 您尚未在任何地方分配此结构。 您需要malloc
它或将其声明为堆栈或全局的struct data d
。
前者可以这样做:
d = malloc(sizeof(struct data));
如果选择后者,访问b
必须写为db
。
您没有为d
分配任何 memory 。 它可能指向无效的 memory 区域等等 - 分段错误。
你可以像这样解决这个问题:
struct data *d = malloc(sizeof(*d));
您在d->b=&key;
行遇到分段错误。 请注意,您尚未将任何 memory 位置分配给结构变量d
。 所以d
包含一些垃圾值,并且d->b
它试图使用该垃圾地址来取消引用指针并获取组件b
。 这是你得到段错误的地方。 要么静态分配结构变量,要么使用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 *
的类型转换。 它是您使用但未分配/初始化的指针变量的非法 memory 引用。
问题是您没有为广告指针分配 memory: struct data *d;
. 此行仅创建一个指针,它不会为它分配 memory。 请尝试以下代码:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.