473,729 Members | 2,177 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Differences between one-dimensional arrays in Java and C

Hi all,

I need to come up with some differences between arrays in Java and C, I have
searched Google and so far all I have found is the following:

Arrays in Java are reference types with automatic allocation of memory. In
C, arrays are groups of variables of the same type in adjacent memory.
Allocation for dynamic arrays is handled by the programmer.

This is an 8 mark question in an old exam paper, so I am assuming there are
more differences, but where can I find them?!

Thank you for your help.

--
Paul Morrison
Nov 14 '05 #1
15 7000
"Paul Morrison" writes:
I need to come up with some differences between arrays in Java and C, I
have searched Google and so far all I have found is the following:

Arrays in Java are reference types with automatic allocation of memory. In
C, arrays are groups of variables of the same type in adjacent memory.
Allocation for dynamic arrays is handled by the programmer.

This is an 8 mark question in an old exam paper, so I am assuming there
are more differences, but where can I find them?!


I would try this search target on google:
<c arrays shortcomings>
Nov 14 '05 #2

"Paul Morrison" <pa**@morrison1 985.freeserve.c o.uk> wrote

I need to come up with some differences between arrays in Java and C, I
have searched Google and so far all I have found is the following:

Arrays in Java are reference types with automatic allocation of memory. In
C, arrays are groups of variables of the same type in adjacent memory.
Allocation for dynamic arrays is handled by the programmer.

This is an 8 mark question in an old exam paper, so I am assuming there
are more differences, but where can I find them?!

A Java array is basically this

struct jdouble1d
{
double *mem;
int size;
};

Evey time you read and write, the java compiler checks against the size
member and throws an exception for out of bounds. Internally it calls
malloc() to allocate the memory, and by some magic the garbage collector
knows when the array goes out of scope and calls free().

A Java 2d array is this

struct jdouble2d
{
struct jdouble1d *mem;
int size;
};

You will see that this has the quirk that not all the sub-arrays need be of
the same length.

What is a C array - just a chunk of memory that the program interprets as
being doubles, or chars, or whatever.
To allocate on the stack you use the notation
double buff[123];

To allocate on the heap you call malloc()

double *buff = malloc(123 * sizeof(double)) ;

If you call malloc() you must call free() manually, the compiler doesn't
have a magic garbage collector that does it for you.

Finally a C 2d arrays are a bit tricky. If we declare

double box[8][10];

we get a chunk of memory containing 800 doubles.

box[3][4] = 1;

and
double box2[800];
box[3 * 10 + 4] = 1;

are essentially equivalent.
However you can also construct a 2d array by calling lots of mallocs().

double **box = malloc(8 * sizeof(double *));
for(i=0;i<8;i++ )
box[i] = malloc(10 * sizeof(double)) ;

and you use the same notation
box[3][4] = 1;

as for the 2d array, despite the fact that the underlying representation is
quite different.

The advantage of Java is that it is impossible to corrupt the computer's
memory, and you d not need to store the array size separately. The advantge
of C is that array accesses compile to direct memory read/writes, and so are
faster.
Nov 14 '05 #3

Malcolm wrote:
"Paul Morrison" <pa**@morrison1 985.freeserve.c o.uk> wrote

I need to come up with some differences between arrays in Java and C, I have searched Google and so far all I have found is the following:

Arrays in Java are reference types with automatic allocation of memory. In C, arrays are groups of variables of the same type in adjacent memory. Allocation for dynamic arrays is handled by the programmer.

This is an 8 mark question in an old exam paper, so I am assuming there are more differences, but where can I find them?!
A Java array is basically this

struct jdouble1d
{
double *mem;
int size;
};

Evey time you read and write, the java compiler checks against the

size member and throws an exception for out of bounds. Internally it calls malloc() to allocate the memory, and by some magic the garbage collector knows when the array goes out of scope and calls free().

A Java 2d array is this

struct jdouble2d
{
struct jdouble1d *mem;
int size;
};

You will see that this has the quirk that not all the sub-arrays need be of the same length.

What is a C array - just a chunk of memory that the program interprets as being doubles, or chars, or whatever.
To allocate on the stack you use the notation
double buff[123];

To allocate on the heap you call malloc()

double *buff = malloc(123 * sizeof(double)) ;

If you call malloc() you must call free() manually, the compiler doesn't have a magic garbage collector that does it for you.

Finally a C 2d arrays are a bit tricky. If we declare

double box[8][10];

we get a chunk of memory containing 800 doubles.

box[3][4] = 1;

and
double box2[800];
box[3 * 10 + 4] = 1;

are essentially equivalent.
However you can also construct a 2d array by calling lots of mallocs().

You can also construct a 2D array by just calling malloc twice.
See C FAQ item 6.16, and look at the second example code.
http://www.eskimo.com/~scs/C-faq/q6.16.html

Also take a look at the following links:
http://code.axter.com/allocate*2darray.h
http://code.axter.com/allocate*2darray.c

double **box = malloc(8 * sizeof(double *));
for(i=0;i<8;i++ )
box[i] = malloc(10 * sizeof(double)) ;

and you use the same notation
box[3][4] = 1;

as for the 2d array, despite the fact that the underlying representation is quite different.

The advantage of Java is that it is impossible to corrupt the computer's memory, and you d not need to store the array size separately. The advantge of C is that array accesses compile to direct memory read/writes, and so are faster.


Nov 14 '05 #4
Malcolm wrote:
What is a C array - just a chunk of memory that the program interprets as
being doubles, or chars, or whatever.
To allocate on the stack you use the notation
double buff[123];

To allocate on the heap you call malloc()

double *buff = malloc(123 * sizeof(double)) ;


The latter is not an array.
Christian
Nov 14 '05 #5
Christian Kandeler <ch************ ****@hob.de_inv alid> writes:
Malcolm wrote:
What is a C array - just a chunk of memory that the program interprets as
being doubles, or chars, or whatever.
To allocate on the stack you use the notation
double buff[123];

To allocate on the heap you call malloc()

double *buff = malloc(123 * sizeof(double)) ;


The latter is not an array.


Sure it is. Specifically, buff is not an array (it's a pointer), but
the object allocated by malloc() is an array (or at least can be
treated as one).

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <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.
Nov 14 '05 #6
"Axter" <te**@axter.com > writes:
Malcolm wrote:
[unrelated stuff snipped]

However you can also construct a 2d array by calling lots of

mallocs().

You can also construct a 2D array by just calling malloc twice.
See C FAQ item 6.16, and look at the second example code.
http://www.eskimo.com/~scs/C-faq/q6.16.html


Now here's an interesting question. I believe it's possible to
construct a 2D array (with both dimensions non-constant) by calling
malloc only once. For example:

T *elements, **array;
size_t element_size = sizeof *elements;
size_t pointer_size = sizeof *array;

size_t element_space = element_size * M * N; /* array is [M][N] */
size_t pointer_space = pointer_size * M; /* only need M pointers */

size_t extra_space = pointer_size-1 - (element_space-1) % pointer_size;
size_t space_needed = element_space + extra_space + pointer_space;

void *memory = malloc( space_needed );

size_t i;

if( memory == 0 ) exit(1);

elements = memory;

array = (T**)memory + (element_space + extra_space) / pointer_size;

for( i = 0; i < M; i++ ){
array[i] = & elements[N*i];
}

/* array now can be used as a 2D array */
/* to free, use 'free( & array[0][0] )' */
Since the memory returned by malloc is suitably aligned for all types,
both 'elements' and 'array' are suitably aligned for objects of their
respective types. Note that 'extra_space' is calculated so that
'element_space + extra_space' is a multiple of 'pointer_size'.

Each of the two areas of memory (at 'elements' and 'array') is used
only to store/retrieve objects of their respective types.

According to my best understanding the code above should work in
standard C. But I put it as a question - does anyone have an argument
to the contrary?

If someone has a supporting argument I'm happy to hear that also. :)
Nov 14 '05 #7
Tim Rentsch wrote:

Now here's an interesting question. I believe it's possible to
construct a 2D array (with both dimensions non-constant) by calling
malloc only once. For example:

[allocate space for elements, padding, and pointers]

Since the memory returned by malloc is suitably aligned for all types,
both 'elements' and 'array' are suitably aligned for objects of their
respective types. Note that 'extra_space' is calculated so that
'element_space + extra_space' is a multiple of 'pointer_size'.

Each of the two areas of memory (at 'elements' and 'array') is used
only to store/retrieve objects of their respective types.

According to my best understanding the code above should work in
standard C. But I put it as a question - does anyone have an argument
to the contrary?


Looks all right. A type's alignment requirement must be
a divisor of its size (otherwise arrays wouldn't work), so the
`extra_space' will be enough padding to get the pointers to
align properly. In fact, `extra_space' may be more than is
needed; if you really want to be parsimonious you can use a
dodge that someone posted here a year or two ago:

#include <stddef.h>
#define alignof(T) offsetof(struct {char c; T t;}, t)

Manually-inserted padding can also be used to write portable
versions of "the struct hack" for C90 implementations (C99
introduced an easier notation).

--
Eric Sosman
esosman#acm-dot-org.invalid
Nov 14 '05 #8
Tim Rentsch wrote:

"Axter" <te**@axter.com > writes:
Malcolm wrote:
[unrelated stuff snipped]

However you can also construct a 2d array by calling lots of

mallocs().

You can also construct a 2D array by just calling malloc twice.
See C FAQ item 6.16, and look at the second example code.
http://www.eskimo.com/~scs/C-faq/q6.16.html


Now here's an interesting question. I believe it's possible to
construct a 2D array (with both dimensions non-constant) by calling
malloc only once. For example:

T *elements, **array;
size_t element_size = sizeof *elements;
size_t pointer_size = sizeof *array;

size_t element_space = element_size * M * N; /* array is [M][N] */
size_t pointer_space = pointer_size * M; /* only need M pointers */

size_t extra_space = pointer_size-1 - (element_space-1) % pointer_size;
size_t space_needed = element_space + extra_space + pointer_space;

void *memory = malloc( space_needed );

size_t i;

if( memory == 0 ) exit(1);

elements = memory;

array = (T**)memory + (element_space + extra_space) / pointer_size;

for( i = 0; i < M; i++ ){
array[i] = & elements[N*i];
}

/* array now can be used as a 2D array */
/* to free, use 'free( & array[0][0] )' */

Since the memory returned by malloc is suitably aligned for all types,
both 'elements' and 'array' are suitably aligned for objects of their
respective types. Note that 'extra_space' is calculated so that
'element_space + extra_space' is a multiple of 'pointer_size'.

Each of the two areas of memory (at 'elements' and 'array') is used
only to store/retrieve objects of their respective types.

According to my best understanding the code above should work in
standard C. But I put it as a question - does anyone have an argument
to the contrary?


Maybe.
Since pointer arithmetic is being done with array,
is it enough for array to be lined up with (T *),
or is the alignment requirement that array be lined up with an
array of (T *), which might have a larger alignment requirement?

I seem to recall that the case of

int i_array_2[2][2] = {0};
int *ptr = (int *)&array;

ptr[3] = 0;

wasn't acceptable to Doug Gwynn and several others on comp.std.c
based on the fact that there was no integer array with four elements,
even though there was certainly an object big enough
and also aligned for int.

--
pete
Nov 14 '05 #9
Eric Sosman <es*****@acm-dot-org.invalid> writes:
Tim Rentsch wrote:

Now here's an interesting question. I believe it's possible to
construct a 2D array (with both dimensions non-constant) by calling
malloc only once. For example:

> [allocate space for elements, padding, and pointers]

[yada yada yada]
Looks all right. A type's alignment requirement must be
a divisor of its size (otherwise arrays wouldn't work), so the
`extra_space' will be enough padding to get the pointers to
align properly. In fact, `extra_space' may be more than is
needed;


Yes it might! Normally the unneed extra space (and even 'extra_space'
itself) won't be too big: I deliberately put the pointer array second
so that at most sizeof(T*)-1 extra space is needed. Usually a few
bytes at most.

if you really want to be parsimonious you can use a
dodge that someone posted here a year or two ago:

#include <stddef.h>
#define alignof(T) offsetof(struct {char c; T t;}, t)

Manually-inserted padding can also be used to write portable
versions of "the struct hack" for C90 implementations (C99
introduced an easier notation).


That's a nice trick. I'll definitely have to add that to my set of
arcane C knowledge.

Strictly speaking the definition shown isn't guaranteed to work. If
sizeof(T) is 8 and alignment_of(T) is 2, the result of alignof(T)
might be 2 or 4 or 6, or even 22. Using GCD( alignof(T), sizeof(T) )
should at least produce a result that is guaranteed to work (right?).
But using GCD still isn't enough to guarantee that the minimum
alignment necessary will result.

Furthermore I can envision cases where it might reasonably not yield
the minimum alignment needed; a compiler might choose to put the 't'
member of the struct above at offset 4 (rather than 2) in an attempt
to get better cache performance, for example.

Despite my protestations, a good technique to know. Thanks.
Nov 14 '05 #10

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

Similar topics

2
8278
by: Daniel | last post by:
Hi, Are there any differences between C# and VB.Net besides syntax? Performance-wise, how do they compare? Thanks, Dan
14
2064
by: Bern | last post by:
what are all the diferences between the two?
2
11842
by: Patrick | last post by:
Are the differences between a search engine, a subject directory and a meta search engine significant for an ebusiness web site owner? A meta search engine merely uses ordinary existing search engines. A subject directory classifies websites into some category. Could anyone point me towards the differences between these three that are significant for an ebusiness web site owner?
13
9634
by: Kieran | last post by:
I am designing a content management system and I want to make sure all pages entered into it's database by users are using valid HTML. I have designed the system to use HTML 4.01 Transitional throughout, however the php powered html checker I have only caters for HTML 4.01 Strict. If possible I need to know the complete differences between Strict and Transitional so I can go through the php script and correctly set it up to properly...
4
3707
by: MS | last post by:
Just a general question here re VBA. Can anyone explain the differences between "!" and "." when refering to a control? eg Me!TxtBox and Me.TxtBox. What is difference between "+" and "&" when working with strings. eg MyStr = "I have " & MyNumber & " apples." and MyStr = "I have " + MyNumber + " apples."
10
1462
by: Brett | last post by:
Are there any books that mainly discuss differences between VB.NET and C#.NET? Possibly situations where you would specifically need/want to use one language over another. Thanks, Brett
4
2818
by: rdemyan via AccessMonster.com | last post by:
I have to import building information from another system. I've decided to keep track of each set of data downloaded by including a Download_Date. That way I keep historical data. My table has 25 fields in addition to Download_Date. My question. I'd like the user to be able to find differences between downloads. The primary key on the table is Building_ID and Download_Date. I'd like a user to be able to select two values for...
16
1503
by: RdS | last post by:
Hello Would someone tell me the differences between following statements? When would you use one over the other? dim objtest1 as car dim objtest2 as new car dim objtest3 as car = new car Are not objtest2 and objtest3 doing the same thing? I understand the =
2
1609
by: Javier | last post by:
Hi, I have just read that struct's in C++ can have public and private members, so I have one question: Which are the differences between classes and structs (besides constructors and destructors?). Thanks.
3
1290
by: gentsquash | last post by:
Inside of <script></script>, inside of <body></body>, what are the differences between document.body.className="mystyle"; and document.body.setAttribute("class", "mystyle"); ? (...assuming that a CSS "mystyle" has been defined.) ================================================================
0
8913
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
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
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
9280
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...
0
9142
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
8144
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...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2162
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.