473,888 Members | 1,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

2D arrays question

csx
Hi everyone!

two quick questions relating to arrays.

Q1,
Is it possible to re-assign array elements?

int array[2][2] = {{2,4}, {4,5}};

array[1][1] = {2,3}

just causes compiler errors! Do I have to assign at the beginning?

Q2,
My other 'main' question relates to 2-Dimensional arrays.

I need to create the size of my 2D array at run time. I have a couple of
functions that provide the dimensions I need. I need to call the function
like:

two_dimensional _array(maxRows, numLeafs)

but then, assign the values after, hence my first question. Can values be
asigned after?

Here is the code I currently have? Is this a good implementation? Any
suggestions would be much appreciated.

int ** myArray = 0; // in C++ 0==NULL

void two_dimensional _array(int rows, int cols)
{
int Rows, Cols;
if (myArray != NULL) {
for (int i = 0; i < Rows; i++) {
myArray[i] = new int[Cols];
}
}
}

int _tmain(int argc, _TCHAR* argv[])
{
myArray = new *int[Rows];
return 0;
}
Jul 19 '05 #1
7 11782
"csx" <cs*@ms.com> wrote in message
news:bl******** **@sparta.btint ernet.com...
Hi everyone!

two quick questions relating to arrays.

Q1,
Is it possible to re-assign array elements?
Yes, individually.

int array[2][2] = {{2,4}, {4,5}};

array[1][1] = {2,3}
Invalid syntax.

Also, array[1][1] denotes a single type 'int' object.
How do you expect to store two values in a single object?

Guessing at which elements you really want to change:

array[1][0] = 2;
array[1][1] = 3;

just causes compiler errors! Do I have to assign at the beginning?
You must assign each element's value individually.
If your values form an appropriate 'pattern' this
can often be done in a loop.
Q2,
My other 'main' question relates to 2-Dimensional arrays.

I need to create the size of my 2D array at run time. I have a couple of
functions that provide the dimensions I need. I need to call the function
like:

two_dimensional _array(maxRows, numLeafs)

but then, assign the values after, hence my first question. Can values be
asigned after?
Yes.
Here is the code I currently have? Is this a good implementation? Any
suggestions would be much appreciated.

int ** myArray = 0; // in C++ 0==NULL
This is not an array, it's a pointer. It does
not point to any storage you can use.
You must allocate some memory and assign its
address to the pointer. I see you tried to
below, but fall short.


void two_dimensional _array(int rows, int cols)
That's not a very desriptive name. I'd call it
e.g. 'load2darray', 'populate2darra y' or something like that.
Also note that you never call this function in the code
you've posted.
{
int Rows, Cols;
Array dimensions should be stored in type 'size_t'
Type 'int' won't necessarily be able to represent
all possible array index values. 'size_t' is
guaranteed to be able to.

if (myArray != NULL) {
for (int i = 0; i < Rows; i++) {
myArray[i] = new int[Cols];
}
}
}

int _tmain(int argc, _TCHAR* argv[])
int main(int argc, char *argv[]) {

No "Windows-isms" allowed here.
myArray = new *int[Rows];
Invalid syntax.

myArray = new int*[Rows];

But this only allocates storage for 'Rows' pointers.
There's still no storage for them to point to.
return 0;
}


The difficulty so many have with arrays is one reason
for the invention of standard library containers such
as std::vector.

I recommend you use containers instead of arrays in
C++ programs, unless there's a compelling reaons to
do otherwise (e.g. interface with C or existing,
nonmodifiable code).

std::vector<std ::vector> > arr2d;

-Can do anything an array can do, and more.
-Does all the memory management for you.
-Is 'flexible' -- will grow or shrink its size as needed.
-Carries its size with it, no need to pass an extra 'size'
to functions as with arrays.

If you insist upon using arrays, perhaps you'll find
useful an example in C I posted to comp.lang.c today. Look
for my name as author of a post in a thread entitled
"Re: How to free allocated memory?"

It uses the C functions 'malloc()' and 'free()' for
memory management, but you should be able to drop in
new[] and delete[] in their place -- you *must* do this
if you're creating arrays of types which have ctors/dtors,
or they won't get called.

But if you don't have to, don't use arrays. Use containers.
Really.

HTH,
-Mike
Jul 19 '05 #2
csx wrote:
Hi everyone!

two quick questions relating to arrays.

Q1,
Is it possible to re-assign array elements?
Of course, unless the elements are 'const'.

int array[2][2] = {{2,4}, {4,5}};

array[1][1] = {2,3}

just causes compiler errors! Do I have to assign at the beginning?
Of course it's an error. The {...} syntax is only for initializers. Why
are you trying to give one element two values anyway?

array[1][1] = 3;

Q2,
My other 'main' question relates to 2-Dimensional arrays.

I need to create the size of my 2D array at run time.
Say no more.

http://www.parashift.com/c++-faq-lit...html#faq-16.19
http://www.parashift.com/c++-faq-lit...html#faq-16.15

The short answer is: Use std::vector.
I have a couple of
functions that provide the dimensions I need. I need to call the function
like:

two_dimensional _array(maxRows, numLeafs)

but then, assign the values after, hence my first question. Can values be
asigned after?

Here is the code I currently have? Is this a good implementation? Any
suggestions would be much appreciated.

int ** myArray = 0; // in C++ 0==NULL
Evil global variable.

void two_dimensional _array(int rows, int cols)
{
int Rows, Cols;
if (myArray != NULL) {
for (int i = 0; i < Rows; i++) {
myArray[i] = new int[Cols];
}
}
}
Why wouldn't you have this function return the pointer rather than
acting on an evil global variable?

Besides that, it seems really broken. Why doesn't it allocate the
initial int* array? Why does it indiscriminatel y overwrite the elements
of the array that myArray points to? What if those pointers already
pointed to dynamic memory?

int _tmain(int argc, _TCHAR* argv[])
_tmain is a reserved identifier in the global namespace (as are all
identifiers beginning with an underscore followed by a lower-case
letter). That means you may not use it as a name in the global
namespace. Also, _TCHAR is reserved in all contexts (as are all
identifiers beginning with an underscore followed by an upper-case
letter or another underscore), and you may not use it at all. In
general, avoid identifier names beginning with an underscore. (And try
posting *standard* C++ code when you post here.)
{
myArray = new *int[Rows];
return 0;
Uh, memory leak? What exactly was this supposed to demonstrate?
}


-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #3
Mike Wahler wrote:


The difficulty so many have with arrays is one reason
for the invention of standard library containers such
as std::vector.

I recommend you use containers instead of arrays in
C++ programs, unless there's a compelling reaons to
do otherwise (e.g. interface with C or existing,
nonmodifiable code).

std::vector<std ::vector> > arr2d;


std::vector<std ::vector<int> > arr2d;

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #4
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:7R******** *********@newsr ead3.news.pas.e arthlink.net...
Mike Wahler wrote:
std::vector<std ::vector> > arr2d;


std::vector<std ::vector<int> > arr2d;


Oops, yes, thanks.

-Mike
Jul 19 '05 #5
csx
Hi, and thanks so much! Ive looked at your array example in C, and it has
been very helpful.
However, there were a couple of things. In this function:

double **alloc2d(size_ t rows, size_t cols)
{
double **result;
size_t row = 0;
size_t col = 0;
if(result = malloc(rows * sizeof *result))
{
if(*result = malloc(rows * cols * sizeof **result)
for(row = 1; row < rows; ++row)
result[row] = *result + row * cols;
else
{
free(result);
result = NULL;
}
}
return result;
}
There is a problem on the lines
if(result = malloc(rows * sizeof *result))
if(*result = malloc(rows * cols * sizeof **result)

There are the errors:
error C2440: '=' : cannot convert from 'void *' to 'double ** '
error C2440: '=' : cannot convert from 'void *' to 'double *'

Not sure how to fix these, can anyone provide advise?
Many 'Thanks' in advance!!
Jul 19 '05 #6
"csx" <cs*@ms.com> wrote in message
news:bl******** **@hercules.bti nternet.com...
Hi, and thanks so much! Ive looked at your array example in C, and it has
been very helpful.
First note that C is not C++. They look very similar
in syntax, the the semantics are different in many
cases. You've just discovered one example of this.

I referred you to that C code for ideas, not
as a 'drop in' C++ solution to your questions.

However, that code I wrote can be made valid C++ with
a simple 'fix'. (actually I'd call it a 'hack').

Or you can configure your compiler to compile
C instead of C++).

See below.
However, there were a couple of things. In this function:

double **alloc2d(size_ t rows, size_t cols)
{
double **result;
size_t row = 0;
size_t col = 0;
if(result = malloc(rows * sizeof *result))
{
if(*result = malloc(rows * cols * sizeof **result)
for(row = 1; row < rows; ++row)
result[row] = *result + row * cols;
else
{
free(result);
result = NULL;
}
}
return result;
}
There is a problem on the lines
if(result = malloc(rows * sizeof *result))
if(*result = malloc(rows * cols * sizeof **result)

There are the errors:
error C2440: '=' : cannot convert from 'void *' to 'double ** '
error C2440: '=' : cannot convert from 'void *' to 'double *'
Those are indeed errors in C++, but not in C.
Not sure how to fix these, can anyone provide advise?
Many 'Thanks' in advance!!


Remember what I wrote:

"It uses the C functions 'malloc()' and 'free()' for
memory management, but you should be able to drop in
new[] and delete[] in their place -- you *must* do this
if you're creating arrays of types which have ctors/dtors,
or they won't get called."

I forgot to add "if you use 'malloc()' you'll need to
cast the return value to the target type"

C allows the conversion from/to 'void*' and any other
pointer type without a cast. But C++ requires a cast:

/* hack: */
if(result = (double**)mallo c(rows * sizeof *result))
if(*result = (double*)malloc (rows * cols * sizeof **result)

I also wrote:
"But if you don't have to, don't use arrays. Use containers.
Really."

And I still stand by that advice.

-Mike
Jul 19 '05 #7
csx
Thanks Mike!
Jul 19 '05 #8

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

Similar topics

19
2862
by: Canonical Latin | last post by:
"Leor Zolman" <leor@bdsoft.com> wrote > "Canonical Latin" <javaplus@hotmail.com> wrote: > > > ... > >But I'm still curious as to the rational of having type > >pointer-to-array-of-size-N-of-type-T (which is fine) and not having type > >array-of-size-N-of-type-T (with some exceptions, which is curious). > > So far > >the consensus seems to be that while everyone is aware of this no one knows
12
1998
by: Samee Zahur | last post by:
Back in the days of old C, only numeric literals could be used as dimensions for statically allocated arrays - the size had to be resolved to a constant at/before compile time. Now I'm beginning to suspect(!) that this is no longer the case either with C or with C++ :( Can anyone upgrade me with the present state/version of rules? (for C++) Exactly, by how many years am I back-dated ???
9
6680
by: Charles Banas | last post by:
i've got an interesting peice of code i'm maintaining, and i'd like to get some opinions and comments on it, hopefully so i can gain some sort of insight as to why this works. at the top of the function (which was translated from Fortran code), among other heinous and numerous declarations, is this bit: static float bbuff; static int bkey; static int buse;
1
2212
by: rir3760 | last post by:
Since a few days ago I have been working with the program I post below (a school assignment). The purpose of the program is to work with the va_ macros (stdarg.h) and arrays of arrays, hopefully learning a little bit in the process. The objective of the fn_memset function is to set all the chars in the arrays passed (of type array N of array M of char) to a specific char, somewhat similar to what the standard function memset does:
15
7027
by: Paul Morrison | last post by:
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
27
2989
by: jacob navia | last post by:
Has anyone here any information about how arrays can be formatted with printf? I mean something besides the usual formatting of each element in a loop. I remember that Trio printf had some extensions but I do not recall exactly if they were meant for arrays. Thanks
3
2570
by: James dean | last post by:
I have created algorithms in C# unsafe code and have fixed the arrays in memory for optimum performance. I use multidimensional arrays rather than jagged arrays. The algorithms i use usually read a bitmap file sequentially so no random accessing different parts of the array. I know in microsoft site it says to use jagged arrays but in this case with reading a sequential file the performance difference will not be as good as a...
41
5003
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in the hash are alphabetically sorted if the key happens to be alpha numeric. Which I believe makes sense because it allows for fast lookup of a key.
16
2556
by: mike3 | last post by:
(I'm xposting this to both comp.lang.c++ and comp.os.ms- windows.programmer.win32 since there's Windows material in here as well as questions related to standard C++. Not sure how that'd go over at just comp.lang.c++. If one of these groups is too inappropriate, just take it off from where you send your replies.) Hi.
0
9800
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
11181
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
10439
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
9597
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
7148
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();...
0
5819
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4642
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
2
4245
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3252
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.