如何在c中从一种类型转换为另一种类型

时间:2010-10-25 08:48:01

标签: c type-conversion

我有以下代码

#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的值,而是获得了特定结构的大小。

5 个答案:

答案 0 :(得分:4)

当我运行代码时(在纠正错误之后),它打印12593.这是49 * 256 + 49 - 换句话说,“11”作为整数(ascii 1是49)。所以我所看到的代码没有任何问题(除了Benoit指出的内存布局假设),所以我们确实需要知道你预期会发生什么

#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;
}

答案 1 :(得分:1)

演员之后

foo* f = (foo*)&b1

你正在解释字符串“11”(ASCII-wise表示为0x31 0x31二进制) 而不是价值11

     +-------------+
f -> | 0x31 | 0x31 |
     +-------------+

     +-------------+
f -> | 0x01 | 0x01 |
     +-------------+

如果你想在演员表之后看到11个类型,你必须做类似

的事情
strcpy(b1.cData,"\x001\x001");

答案 2 :(得分:0)

执行代码后,结构栏看起来像这样

| 0x31 | 0x31 | 38 * Rubish .... |

将它转换为foo会将其解释为int。当您以十六进制打印时,您将看到与此类似的输出:

printf("Type is  %x \n",f->Type); 
Type is  b7003131 

答案 3 :(得分:0)

你的演员foo *f=(struct foo *)&b1;是错的,因为你有一个typedef foo,而不是一个struct foo。请改用foo *f=(foo *)&b1;。即不要使用它,因为它违反了严格的别名规则并且是未定义的行为。

您将数据写为字符串并将其读取为int,这是下一个未定义的行为。

strcpy只向结构写入3个字节(两个字符和终止\ 0)。假设32位整数,int的第四个字节仍然是不确定的。读取不确定的值也是未定义的行为。

无论你得到什么输出都不足为奇,因为一切都被允许在未定义的行为上发生。

答案 4 :(得分:0)

您正在尝试将指向foo(* f)的指针指向另一个结构“bar”。 foo将无法指向此类型。 因此,您将无法将一个结构转换为另一个结构。

指针只能指向用于指针声明的数据。

试试这个:

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

typedef struct {
  char s[8];
}bar;

int main()
{
  bar b1;
  strcpy(b1.s,"0x01020304");
  foo *f=(struct foo *)&b1;
  printf("Type is  %d \n",f->Type);
  return 0;
}
相关问题