Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Unwarranted assumptions about storage

Node:Unwarranted assumptions about storage, Next:, Previous:Confusing foo++ and ++foo, Up:Run-time errors



Unwarranted assumptions about storage

Do not assume that the size of a structure is the sum of the sizes of its parts. The two may differ for various reasons; for example, the operating system may be aligning variables with specific addresses within the data structure. Furthermore, the elements of an array may not even be next to one another in memory.

This kind of code is always safe:

int my_array[3];

my_array[0] = 0;
my_array[1] = 0;
my_array[2] = 0;

This kind of code is not:

int my_array[3];

*my_array = 0;
*(my_array + (1 * sizeof(int))) = 0;
*(my_array + (2 * sizeof(int))) = 0;

While it is true that the variable my_array used without its square brackets is a pointer to the first element of the array, you must not assume that you can simply calculate a pointer to the third element with code like the following:

my_array + 2 * sizeof(int);

Do something like this instead:

&(my_array[2]);

 
 
  Published under free license. Design by Interspire