如何从一种类型转换到另一个在C [英] how to cast from one type to another in c

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

问题描述

我有以下code

#include <stdio.h>
#include<ctype.h>

typedef struct {
  int Type;
  int Type2;
}foo;

typedef struct {
  char cData[40];
}bar;

int main()
{
  bar b1;
  strcpy(b1.cData,"11");
  foo *f=(struct foo *)&b1;
  printf("Type is  %d \n",f->Type);
  return 0;
}

但我没有得到f中的指针类型1的值,而不是我得到了particuler结构的大小。

But i am not getting the value of type 1 in f's pointer , instead i am getting size of that particuler struct.

推荐答案

当我运行code(修正错误后),它打印12593.这是49 * 256 + 49 - 换句话说,11 作为一个整数(即49 ASCII 1)。所以没有错code,据我所看到的(除了内存布局的假设所指出的伯努瓦),所以我们需要知道你期望发生

When I run the code (after correcting for errors), it prints 12593. Which is 49*256 + 49 - in other words, "11" as an integer (ascii 1 being 49). So nothing wrong with the code as far as I can see (apart from the memory layout assumptions pointed out by Benoit), so we do need to know what you expected to happen

#include <stdio.h>
#include<ctype.h>

typedef struct {
  int Type;
  int Type2;
}foo;

typedef struct {
  char cData[40];
}bar;

int main()
{
  bar b1;
  foo *f=(foo *)&b1;
  strcpy(b1.cData,"11");
  printf("Type is  %d \n",f->Type);
  return 0;
}

这篇关于如何从一种类型转换到另一个在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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