Jump to content

[SOLVED] Theoretical doubt matrices in C

- - - - -

  • This topic is locked This topic is locked
4 replies to this topic

#1
charles-eng

charles-eng

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
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.

#2
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
>>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.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#3
charles-eng

charles-eng

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
I see, thanks man.

#4
kernelcoder

kernelcoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 282 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal
Yes, they are stored in memory address one after another.


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
charles-eng

charles-eng

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
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