Nikita Nikita
Nikita Nikita

Reputation: 1

What actually is going on when we do structure type casting?

Here (how to cast from one type to another in c) we have nearly the same question but without explanation how structure type casting works.

#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"); 
  (struct foo *) &b1;  // What is going on here? What have changed at this point?
  return 0;
}

We have different sizes - sizeof (foo) > sizeof (bar). So what is happened after casting?

Upvotes: 0

Views: 66

Answers (1)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

You cannot cast one structure type into another. You can only cast a pointer to one structure type to point to another, in which case nothing actually happens to it--it's just a memory address, and it is re-interpreted as pointing to a different kind of thing.

Upvotes: 2

Related Questions