简体   繁体   English

如何在 C 中打印 (void **) 数据?

[英]How can I print a (void **) data in C?

I'm having a hard time fully understanding and learning the behavior of pointers, casts, and all that.我很难完全理解和学习指针、强制转换等的行为。

I have the following struct, which is basically a stack data structure :我有以下结构,它基本上是一个stack data structure

struct stack
{
    void **items;
    size_t top;      
    size_t max_size;
};

I want to be able to return the top element , so this is my Peek function:我希望能够返回top element ,所以这是我的Peek function:

void *Peek(const stack_ty *stack)
{
    return(stack->items[stack->top]);
}

And this is my testing print in main.c :这是我在main.c中的测试打印:

stack_ty *new_stack = CreateStack(5);
 
Push(new_stack, (void *)1);
Push(new_stack, (void *)2);
Push(new_stack, (void *)3);
 
printf("The top element is %d\n", *(int *)Peek(new_stack));

I'm getting a Segmentation fault (core dumped) right after it enters the Peek function.我在进入Peek function 后立即遇到Segmentation fault (core dumped)

I can guess it is related to the *(int *) cast I did to the return value of Peek() , but I can't think about any other way to print() or show any value that is passed by void * .我可以猜测它与我对Peek()的返回值所做的*(int *)强制转换有关,但我想不出任何其他方式来print()或显示任何由void *传递的值。 I mean, I have to cast it to int * or char * or whatever, right?我的意思是,我必须将它转换为int *char *或其他什么,对吧?

What am I doing wrong here?我在这里做错了什么? I'll be glad to hear any tips on how to better understand this whole pointers thing.我很高兴听到有关如何更好地理解整个pointers的任何提示。 I mean, I thought I was pretty good at it, but I guess I was wrong.我的意思是,我以为我很擅长,但我想我错了。

To be honest, in the beginning I thought I needed to cast 1,2 and 3 to (void *)&1 , (void *)&2 , (void *)&3 , because I thought I can't pass them just like that, and I thought that if I want to cast an int to a void * I have to give it the address of the int .老实说,一开始我认为我需要将1,2 and 3转换为(void *)&1(void *)&2(void *)&3 ,因为我认为我不能像那样通过它们,我想如果我想将int转换为void *我必须给它intaddress

But the compiler screamed at me, so I changed it to Push(new_stack, (void *)3);但是编译器对我大喊大叫,所以我把它改成了Push(new_stack, (void *)3);

Since you're casting an int to a void * when you push, you need to cast it back to an int when you peek, not to an int * .由于您在推动时将int转换为void * ,因此您需要在查看时将其转换回int ,而不是int * You're not storing a pointer to an integer in the stack, you're treating the integer itself as if it were a pointer.您没有在堆栈中存储指向 integer 的指针,而是将 integer 本身视为指针。

printf("The top element is %d\n", (int)Peek(new_stack));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM