Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structpointer to array address

Is it okay to give the address of a character array to a struct pointer ?

  typedef struct {
  int ID;
  word32 Myports;
  stripports gd[256] ;
  }Table;

  typedef struct {
  oldxmd used;
  newip  ip;
  newxmd new;
  }stripports;

  char buffer1[256];

  Table *tableptr = buffer1 ;

  tableptr ->ID = 15 ;
  tableptr ->Myports= somenumber ;
  tableptr ->gd[0].used = somenumber ;

The tough part is that I am not able to relate why the tableptr would accept an array start address ! My best bet is that the above code is not correct or is unsafe .

Although casting was adopted later on but why does it accept an array ?

 Table* tableptr = (Table*)buffer1;

Table *tableptr = buffer1 ; was replaced by Table* tableptr = (Table*)buffer1; in many tests that followed.

Without casting , Can a struct pointer take values other than the address of the newly created pointee struct ?

I have a series of test written by many authors in the repository and its really confusing .

like image 644
Borrito Avatar asked Feb 12 '26 08:02

Borrito


1 Answers

Assigning the address of a character array to a struct pointer is not guaranteed to work, there may be alignment issues. Some architectures only allow ints to be aligned on even addresses while character arrays usually can start at any address.

There is also the buffer overrun issue. If the the Table type is bigger then the character array, you may end up overwriting other variables or getting a memory protection errors.

Both these issues can be overcome by changing

char buffer1[256];

to

char *buffer1 = (char*)malloc(sizeof Table);
like image 123
Klas Lindbäck Avatar answered Feb 14 '26 21:02

Klas Lindbäck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!