Hi, when I define a matrix in C it's elements are guaranteed to be stored one next to the other, right?
As an example would char mat[2][2] = { {1,2},{0,2}} be stored in memory like this : 1 2 0 2 ?
Thanks in advance.
4 replies to this topic
#1
Posted 11 February 2012 - 04:55 PM
|
|
|
#2
Posted 12 February 2012 - 07:00 AM
>>it's elements are guaranteed to be stored one next to the other, right?
No. There is no such guarantee. The only thing that can be said for certain is that the data is stored in one continuous block of memory. How that memory is laid out is compiler and operating system dependent. We can't even say for certain how an individual integer is represented in memory. If you have a 4 byte integer, some operating systems has it in memory as byte numbers 1, 2, 3 and 4, while others may represent them in reverse order, e.g. 4, 3, 2 and 1. That's called endianness.
No. There is no such guarantee. The only thing that can be said for certain is that the data is stored in one continuous block of memory. How that memory is laid out is compiler and operating system dependent. We can't even say for certain how an individual integer is represented in memory. If you have a 4 byte integer, some operating systems has it in memory as byte numbers 1, 2, 3 and 4, while others may represent them in reverse order, e.g. 4, 3, 2 and 1. That's called endianness.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.
#3
Posted 14 February 2012 - 01:38 PM
I see, thanks man.
#4
Posted 06 May 2012 - 06:53 PM
Yes, they are stored in memory address one after another.
Case 1:
Case 2:
So yes, the conclusion is that the stacked memory of arrays in C/C++ are contiguous.
The 'Contiguous memory of array' and 'endianness' are different things.
Case 1:
char mat[2][2] = { {1,2},{0,2}};
char *add1 = &mat[0][0];
char *add2 = &mat[0][1];
char *add3 = &mat[1][0];
char *add4 = &mat[1][1];
As example, in a 32 machine with msvc9 compiler, the values for add1/2/3/4 are 0x0012ff20, 0x0012ff21,0x0012ff22,0x0012ff23.Case 2:
int mat[2][2] = { {1,2},{0,2}};
int *add1 = &mat[0][0];
int *add2 = &mat[0][1];
int *add3 = &mat[1][0];
int *add4 = &mat[1][1];
On the same machine the values for add1/2/3/4 are 0x0012ff14, 0x0012ff18,0x0012ff1c,0x0012ff20. Note that the differences between two addresses are 4 (the size of int in msvc9 compiler).So yes, the conclusion is that the stacked memory of arrays in C/C++ are contiguous.
The 'Contiguous memory of array' and 'endianness' are different things.
#5
Posted 08 May 2012 - 03:34 PM
Thanks, I suppossed they were stored that way. It's good to know.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

This topic is locked
Back to top










