Вы получаете ошибку сегментации в строке 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 *
, который вызывает ошибку.Это недопустимая ссылка на память переменной-указателя, которую вы использовали, но не распределили / инициализировали.