"Janice" <> writes:
> My working system requires the starting address of a piece of data (an int,
> a long, etc.) must be a multiple of 4. If the requirement is not met, a
> segmentation fault occurs.
Ok. That's pretty common.
> My question is the following.
> For example,
> int a = buf[x]; //The buf is an int array
> How come the x must be a multiple of 4?
What makes you think x needs to be a multiple of 4? If buf is
declared as an int array, you can access any element as an int, and
each element will be properly aligned. The compiler will take care of
this for you.
Here's a program that illustrates what's going on:
#include <stdio.h>
int main(void)
{
int buf[20] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3,
5, 8, 9, 7, 9, 2, 3, 2, 8, 4 };
int i;
i = buf[0]; /* no problem */
printf("buf[0] = %d\n", i);
i = buf[1]; /* no problem */
printf("buf[1] = %d\n", i);
i = buf[19]; /* again, no problem */
printf("buf[19] = %d\n", i);
printf("Address of buf[0] is %p\n", (void*)&buf[0]);
printf("Address of buf[1] is %p\n", (void*)&buf[1]);
printf("Address of buf[19] is %p\n", (void*)&buf[19]);
return 0;
}
I ran it on a system with characteristics similar to yours (8-bit
bytes, 32-bit int, 4-byte alignment for int), and got the following
output:
buf[0] = 3
buf[1] = 1
buf[19] = 4
Address of buf[0] is 0x22eec0
Address of buf[1] is 0x22eec4
Address of buf[19] is 0x22ef0c
Both the values of the addresses and the output format of the "%p"
option are system-specific. On this system, addresses are displayed
in hexadecimal, and you can tell from the output that all the
addresses are 4-byte aligned.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.