473,699 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Allocation of memory for arrays, hoe does it work?

I have a question regarding where memory is allocated when arrays are
created. I'll illustrate this by example. I may be wrong on some
details, do feel free to correct me.

The code piece:

int p[3][3];

Creates a 2dimensional array. p can be thought of as a pointer,
containing the adres of the first element in the array. The memory is
allocated in one sequence, so

p[x][y];

would mean: 'the integer at adress p + (x + 3*y)*sizeof(int )'. So far i
understand how memory is allocated, but what happens when I dynamically
allocate a 2d array?

int **n;
*n=new int[3];
for (int i=0; i<3; i++) n[i]=new int[3];

Here, the memory can't be in a sequence since the compiler at line (2)
impossably can know how much memory will be allocated for each of the
pointers p[i]. So my best guess for the memory allocation here is that
line (2) allocates an array of three pointer-to-int and stores the
adress of the first element in p. In line (3), each of these pointers in
p[i] are set to point at the first element of an array of three int:s.
These three int-arrays need not be allocated anywhere near each other,
right? The memory would therefor be allocated in a very different way
than the simple int p[3][3] array, and i can accept this as I am now
dealing with pointers and not an array, but what does

n[x][y]

mean? how is this interpreted? Has the [] operators been overloaded or
am I totally wrong in my guess for where memory is allocated?

Also, the dynamically callocated array would need mor memory, wouldn't
it? apart form the 9 stored integers (18 bytes), it would also require
4*4 bytes for the pointers n and n[i] (on a Win32 machine, the memory
adress is 4 bytes, isn't it?)

regards
hall
--
( - Remove capital X from email to reply - )

Jul 19 '05 #1
2 5338


hall wrote:

I have a question regarding where memory is allocated when arrays are
created. I'll illustrate this by example. I may be wrong on some
details, do feel free to correct me.

The code piece:

int p[3][3];

Creates a 2dimensional array. p can be thought of as a pointer,
containing the adres of the first element in the array.
But note: p is *not* a pointer.
You have the right idea, but this sentence may be misleading to
other newbies.
The memory is
allocated in one sequence, so

p[x][y];

would mean: 'the integer at adress p + (x + 3*y)*sizeof(int )'. So far i
understand how memory is allocated, but what happens when I dynamically
allocate a 2d array?

int **n;
*n=new int[3];
n = new int* [3];
for (int i=0; i<3; i++) n[i]=new int[3];

Here, the memory can't be in a sequence since the compiler at line (2)
impossably can know how much memory will be allocated for each of the
pointers p[i]. So my best guess for the memory allocation here is that
line (2) allocates an array of three pointer-to-int and stores the
adress of the first element in p. In line (3), each of these pointers in
p[i] are set to point at the first element of an array of three int:s.
These three int-arrays need not be allocated anywhere near each other,
right? The memory would therefor be allocated in a very different way
than the simple int p[3][3] array, and i can accept this as I am now
dealing with pointers and not an array,
an image is worth 1000 words.

int p[2][3] looks in memory like this:
p
+---+---+---+---+---+---+
| | | | | | |
+---+---+---+---+---+---+

| | | |
+--- 3 ---+ +--- 3 ---+

| |
+---- 2 times ---+
while

int **n;
n = new int* [2];
for( int i = 0; i < 2; ++i ) n[i] = new int [3];

looks like this

n
+-----+ +------+ +---+---+---+
| o---------->| o---------------->| | | |
+-----+ +------+ +---+---+---+
| o---------+
+------+ | +---+---+---+
+--->| | | |
+---+---+---+
but what does

n[x][y]

mean? how is this interpreted? Has the [] operators been overloaded or
am I totally wrong in my guess for where memory is allocated?
No. Array indexing in C is defined to be:

n[x] = *(n+x);

thus array indexing is defined in terms of pointer arithmetic. That's
why the above works.

Take the address stored in n. Add x (adjusted to the data
type size) and add it to n. Use this new pointer to look
up the memory.

so a[i] works completely different, depending on what a really
is. If it is a fixed size array, then the compiler knows where
in memory the array is located. The compiler adds x to that location
and uses that for the lookup.

If on the other hand the array a has been dynamically allocated, then
the lookup works a little bit different: locate a, fetch the starting
address from there, add the index and use the result for the lookup.

Note: Under the hood there is one more lookup in the second version,
yet you use always the same C syntax: a[i].

Also, the dynamically callocated array would need mor memory, wouldn't
it?
Look up the image. Yes it would.
apart form the 9 stored integers (18 bytes), it would also require
4*4 bytes for the pointers n and n[i] (on a Win32 machine, the memory
adress is 4 bytes, isn't it?)


Yes.
Note: It is undefined how many bytes are needed to store something.
You could express the above as:

in the dynamic case there would be 9 * sizeof(int) bytes for the data
+ 3 * sizeof(int*) bytes for the pointer array
+ 1 * sizeof(int**) bytes for the starting pointer.

Now that would be true on every machine and everybody could still see
that that would require more memory then 9 * sizeof(int) for the
static case.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #2
Ron Natalie wrote:
While you can write
int (*n)[3] = new int[3][3];
There's no way to declare n for a runtime determined size.

The size of the first dimension can be determined at run-time,
as in

void f (int size)
{
int (* n) [3] = new int [size][3];
// ...
delete [] n;
}

Think of n as a one-dimensional dynamic array whose
value-type is int [3]. So we're passing `size', but
not `3', as an argument of `operator new []'.

The value-type must be completely known at compile
time to make pointer arithmetic operations well defined.

Dynamically allocated arrays would not be necessary if
their size had to be a compile-time constant. We could
dynamically allocate an instance of an appropriate
struct instead.

Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7663
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray = (data_type**)malloc(widht*height*sizeof(data_type)+ height* sizeof(data_type*)); //allocate individual addresses for row pointers. Now that I am moving to C++,am looking for something by which I can
1
2384
by: Roberto Dias | last post by:
I'm a newbie in C++ programming. I bought a book yet and I have learned by means internet donwloadble materials. I feel not confortable using multi-dimensional arrays. I simply cannot understand memory allocation principle. I have got some ideas that require this one, but only thoughts and no action I have done. Unfortunately, the Deitel book don't explore this topic well. Vectors? How to use them insted of multi-dimensional arrays? What...
6
8206
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new DestinationAddress(); // code 1
5
3680
by: Uday Joshi | last post by:
Hi look at the code below /* test.c */ int main(int argc, char *argv) { int *x; *x = 10; printf("%d\n", *x); return 0;
11
3044
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
4
5065
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or deleted, however it must be initialized by a function during run-time to contain so many users which each contain so many directories of which each contain so many files. I've completed the program and have it running flawlessly without implementing...
9
2510
by: weidongtom | last post by:
Hi, I've written the code that follows, and I use the function add_word(), it seems to work fine *before* increase_arrays() is called that uses realloc() to allocate more memory to words. But *after* calling increase_arrays(), I received segmentation fault. I tried to step it through gdb, and I found out that after calling increase_arrays(), words's original value is modified, and if I tried to access it, I get <address 0x11 out of...
7
3892
by: nw | last post by:
Hi, We've been having a discussion at work and I'm wondering if anyone here would care to offer an opinion or alternative solution. Aparently in the C programming HPC community it is common to allocate multidimentional arrays like so: int *v_base = (int *) malloc(1000000*sizeof(int)); int **v = (int **) malloc(1000*sizeof(int *));
5
8007
by: David Golightly | last post by:
Quick question for the gurus out there: in ECMAScript, one can create a new Array object with a length like so: var animals = new Array(128); This creates a new Array object with a "length" property set to 128. My question: Does this in any sense "preallocate" memory for any of these 128 slots? I've seen the word "preallocate" bandied about, but my experience with UAs tells me this term is being misused; all 128 of those "slots"...
0
8691
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9180
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9038
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8920
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8887
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7755
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3060
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2012
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.