如何在C中转换变量? [英] How do I cast a variable in C?

查看:86
本文介绍了如何在C中转换变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



所以我是一名学生在C学习编程。最近,在我的编程课上,我一直在处理以下问题:



将h投射到4种不同类型的指针,可以安全地投射到。对于每种类型的指针,显示如何访问数组b的索引5处的整数。



Hi everyone,

So I am a student learning programming in C. Recently, in my programming class, I have been tackling the following question:

Cast h to the 4 different types of pointers it is safe to cast h to. For each type of pointer show how to access the integer at index 5 of array b.

struct baz g;
void * h = &g;

The structures consist of the following:

struct foo{
  int a;
  int b[20];
};

struct bar{
  struct foo c;
  char d[20];
};

struct baz{
  struct bar e;
  struct foo f;
};





如果我能得到这个问题的帮助,我将非常感激。提前致谢!



我尝试过的事情:



我有关于转换的谷歌搜索示例,但这个问题要复杂得多。



If I could get help with this question, I will really appreciate it. Thanks in advance!

What I have tried:

I have Googled examples on casting, but this problem is much more complicated.

推荐答案

我们不做你的作业:它是有原因的。它就是为了让你思考你被告知的事情,并试着理解它。它也在那里,以便您的导师可以识别您身体虚弱的区域,并将更多的注意力集中在补救措施上。

亲自尝试,您可能会发现它并不像您想象的那么难! />


如果您遇到特定问题,请询问相关问题,我们会尽力提供帮助。但是我们不会为你做这一切!

所以想想你要投入什么,然后决定你可以施展什么。

因为 h 被分配一个指向 g 的指针,这是 baz ,你可以把它投射到 baz 。因为 baz 开头,所以你也可以将它投射到那里。因为 bar foo 开头,所以您也可以将其强加给它。等等。

一旦你投了它们,你就已经知道如何访问它们了!
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.
Try it yourself, you may find it is not as difficult as you think!

If you meet a specific problem, then please ask about that and we will do our best to help. But we aren't going to do it all for you!
So think about what you are casting to what, and decide what you can cast h to.
Because h is assigned a pointer to g which is a baz, you can cast it to a baz. Because the baz starts with a bar, you can cast it to that as well. Because a bar starts with a foo, you can cast it to that as well. And so on.
Once you've cast them, you already know how to access them!


这篇关于如何在C中转换变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆