C 将结构内部使用的void*指针类型转换为int*指针时出现问题!
我的代码如下:C 将结构内部使用的void*指针类型转换为int*指针时出现问题!,c,C,我的代码如下: #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); } #包括 结构数据 { INTA; 无效*b; }; int mai
#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);
}
#包括
结构数据
{
INTA;
无效*b;
};
int main()
{
结构数据*d;
int*ptr;
int键=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
必须写为d.b
您没有为d
分配任何内存。它可能指向一个无效的内存区域和一个分段错误
您可以这样解决此问题:
struct data *d = malloc(sizeof(*d));
问题是您没有为d指针分配内存:
structdata*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);
}
在d->b=&key;行中出现分段错误代码>请注意,您尚未为结构变量d
分配任何内存位置。因此d
包含一些垃圾值,d->b
它试图使用该垃圾地址取消对指针的引用并获取组件b
。这就是你的错误所在。静态分配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*
导致segfault。它是指针变量的非法内存引用,您已经使用了该变量,但尚未分配/初始化。您希望d->b指向什么?请只发布正确缩进的代码不要强制转换malloc
的返回值。