473,385 Members | 1,331 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Dynamic allocaiton of a 2D-array

Hello!

Again a silly pointer-problem! For a simple ASCII-game I am planning to
code, I wrote the following routine to allocate memory for the viewport:

--

bool allocate_viewport (world_square ***vis_squares, int rows, int cols)
{
int i;

*vis_squares = (world_square**) malloc(rows * sizeof(world_square*));

if (vis_squares == NULL) {
return false;
}
for (i=0; i<25; i++) {
*vis_squares[i] = (world_square*) malloc(cols *
sizeof(world_square));
if (*vis_squares[i] == NULL) {
return false;
}
}
return true;
}

--

Where world_square is the typedef of a struct containing some info on
the world tile (longs and ints basically). The goal is to be able to
access viewable tiles by simply using array notation as in
vis_squares[x][y]. In other words: I want to allocate memory for a
2D-array containing the viewable tiles.

This function is invoked in main.c in the following manner;

world_square **vis_squares;
if (!initialize()) {
printf("ERROR: Failed to initialize\n");
return 1;
}
allocate_viewport (&vis_squares,25,80);

But it (ofcourse) fails horribly: windows (XP pro) bails with a useless
error message. What am I doing wrong here? I am at loss. Running the app
through GDB doesn't help me much, except noting that it fails at i=2...

Thanks for your time,

John den Haan
Feb 10 '07 #1
4 3667
In article <be***************************@news.chello.nl>,
John den Haan <no****@nospam.comwrote:
>
bool allocate_viewport (world_square ***vis_squares, int rows, int cols)
{
int i;

*vis_squares = (world_square**) malloc(rows * sizeof(world_square*));

if (vis_squares == NULL) {
return false;
}
for (i=0; i<25; i++) {
*vis_squares[i] = (world_square*) malloc(cols *
sizeof(world_square));
if (*vis_squares[i] == NULL) {
You meant (*vis_squares)[i] but you wrote *vis_squares[i] which actually
means *(vis_squares[i]). Since vis_squares (the triple-pointer) only points
to a single double-pointer (the one declared in the caller), vis_squares[i]
doesn't point to a valid object for any value of i other than 0. So you
corrupted some unrelated memory and the program crashed.

And shouldn't that 25 be rows?
return false;
}
}
return true;
}
[...]
>
world_square **vis_squares;
if (!initialize()) {
printf("ERROR: Failed to initialize\n");
return 1;
}
allocate_viewport (&vis_squares,25,80);
--
Alan Curry
pa****@world.std.com
Feb 10 '07 #2
Alan Curry schreef:
You meant (*vis_squares)[i] but you wrote *vis_squares[i] which actually
means *(vis_squares[i]). Since vis_squares (the triple-pointer) only points
to a single double-pointer (the one declared in the caller), vis_squares[i]
doesn't point to a valid object for any value of i other than 0. So you
corrupted some unrelated memory and the program crashed.
Thank you! I really needed an extra pair of eyes on that one :)
And shouldn't that 25 be rows?
Yes it should be ;) Thanks again for your sharpness.

- John
Feb 10 '07 #3
On Sat, 10 Feb 2007 04:09:02 +0100, John den Haan <no****@nospam.com>
wrote:
>Hello!

Again a silly pointer-problem! For a simple ASCII-game I am planning to
code, I wrote the following routine to allocate memory for the viewport:

--

bool allocate_viewport (world_square ***vis_squares, int rows, int cols)
{
int i;

*vis_squares = (world_square**) malloc(rows * sizeof(world_square*));
Make life easier on yourself:

Don't cast the return from malloc to a pointer type. It never
helps and could hide a diagnostic you would really want to see.

Let the operand of sizeof be variable being assigned preceded
by *, as in:
*vis_squares = malloc(rows * sizeof **vis_squares);
>
if (vis_squares == NULL) {
You probably meant *vis_squares.
return false;
}
for (i=0; i<25; i++) {
You want rows here, not 25.
*vis_squares[i] = (world_square*) malloc(cols *
sizeof(world_square));
After fixing the precedence problem, this would become
(*vis_squares)[i] = malloc(cols * sizeof *(*vis_squares)[i];
if (*vis_squares[i] == NULL) {
Another precedence problem.
return false;
}
}
return true;
}

Remove del for email
Feb 11 '07 #4
>On Sat, 10 Feb 2007 04:09:02 +0100, John den Haan <no****@nospam.com>
>wrote:
>>bool allocate_viewport (world_square ***vis_squares, int rows, int cols)
{
int i;

*vis_squares = (world_square**) malloc(rows * sizeof(world_square*));
In article <7l********************************@4ax.com>,
Barry Schwarz <sc******@doezl.netwrote:
>Make life easier on yourself:

Don't cast the return from malloc to a pointer type. It never
helps and could hide a diagnostic you would really want to see.

Let the operand of sizeof be variable being assigned preceded
by *, as in:
*vis_squares = malloc(rows * sizeof **vis_squares);
Agreed. I would also add, however, that one can make this even
easier, by making a local "world_square **" pointer:

bool allocate_viewport(world_square ***resultp, int rows, int cols) {
bool failed = false;
world_square **squares;
int i;

squares = malloc(rows * sizeof *squares);
if (squares == NULL)
failed = true;
else {
for (i = 0; i < rows; i++) {
squares[i] = malloc(cols * sizeof *squares[i]);
if (squares[i] == NULL) {
failed = true;
break;
}
}
if (failed) {
/* release the ones we successfully allocated */
while (--i >= 0)
free(squares[i]);
/* and the array itself */
free(squares);
squares = NULL;
}
}
*resultp = squares;
return !failed;
}

One might also be able to improve this by doing just two malloc()s:

bool allocate_viewport(world_square ***resultp, int rows, int cols) {
world_square **squares;
int i;

/* allocate enough space for row-pointers */
squares = malloc(rows * sizeof *squares);
if (squares != NULL) {
/* allocate enough space for all rows*cols data, at once */
squares[0] = malloc(rows * cols * sizeof *squares[0]);
if (squares[0] != NULL) {
/* make nonzero row pointers point to the appropriate part */
for (i = 1; i < rows; i++)
squares[i] = squares[0] + (i * cols);
} else {
/* give up row pointers since we cannot get data space */
free(squares);
squares = NULL;
}
}
*resultp = squares;
return squares != NULL;
}

This depends on the rest of the code: it makes the assumption that
there is no need to replace a given row without disturbing other
rows. (That is, if each row is separately malloc()ed, any row can
be replaced at any point:

old = squares[some_row];
new = malloc(...); /* some new row */
if (new == NULL) ... do something ...

/* insert desired processing here, then: */
squares[some_row] = new;
free(old);

If squares[some_row] is critically dependent on squares[0], as is
the case with the two-malloc() method, this is no longer possible.)

Yet another improvement is to get rid of the "bool" return value
entirely, and simply return the "world_square **" value (non-NULL
means success, NULL means failure). This eliminates the need for
the "world_square ***resultp" parameter.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Feb 12 '07 #5

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

Similar topics

14
by: John Hunter | last post by:
I have a list of two tuples containing x and y coord (x0, y0) (x1, y1) ... (xn, yn) Given a new point x,y, I would like to find the point in the list closest to x,y. I have to do this a...
0
by: beliavsky | last post by:
xiaohua_sun@yahoo.com (SunX) wrote in message news:<337e6cd5.0405291411.4376debc@posting.google.com>... > What is the best way to assign a 2d lists? Something like; > > for i in range(10): > ...
0
by: Simena Dinas | last post by:
KToon: 2D Animation Toolkit KToon is a 2D Animation Toolkit designed by animators (Toonka Films) for animators, focused to the Cartoon's industry. This project is covered by the GPL License...
2
by: Shamli | last post by:
I am looking for an algorithm that enlarge a 2D polygon. cheers,
1
by: Jesper | last post by:
Hi, 1. I've search the net for some great usercontrols where I can plot data, draw graphs in both 2d and 3d. I've not had that much of success in my search, and I'm considering writing my own....
6
by: Dan V. | last post by:
I would like to create a 2D string list (2D ArrayList ???). I would like to pass in a table or query as a parameter and have both columns transform into a 2D ArrayList. When I sort the one...
7
by: Matt | last post by:
Hi All, I have a little piece of code that is giving me the shits. I have an arraylist colelction which is putting dynmaic objects into it, and the objects are being accessed dynamically too. My...
5
by: Jack Nielsen | last post by:
Does anyone have a link to Visual Studio 2005 directcx 2d sprite manipulation or just simple graphics with directx 2d. Jack ...
4
by: Jon Harrop | last post by:
I am writing a 3D graphing component built upon WPF and would like to have 2D vector graphics (e.g. typeset mathematics) as labels laid out from 3D coordinates. For example, a tick on an axis has a...
6
by: raphfrk | last post by:
While I am here, I just thought I'd ask if there is a recommended way of handling 2d dynamic arrays. I implement them using the following kind of code. ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.