473,715 Members | 3,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems initializing a dynamically allocated 2D array

I am having lots of trouble getting a simple program that initializs a
dynamically allocated 2D array to work. My 2D array is not getting
initialized properly, and additionally I am getting a "Null pointer
assignment" error. Kindly help.

Also, eventually I intend to move this logic to a separate function.
For that, I believe, that I will need to pass a
pointer-to-pointer-to-pointer type as an arguent. Please confirm.

[My apologies to C purists --- I am using the new operator instead of
malloc/calloc since I find its usage more intuitive]

Masood

/*************** *************** *************** *************** ************/
#include <stdio.h>

#define ROWS 3
#define COLUMNS 5
main()
{
int **tbl;
size_t rows = ROWS;
size_t cols = COLUMNS;
int startVal = 2;

tbl = new (int**)[cols];

for(size_t i = 0; i < rows; i++)
tbl[i] = new (int *)[rows];

for(size_t i1 = 0; i1 < rows; i1++)
for(size_t j1 = 0; j1 < cols; j1++)
tbl[i1][j1] = startVal++;

for(size_t i2 = 0; i2 < rows; i2++)
for(size_t j2 = 0; j2 < cols; j2++)
printf("Row: %d, Col: %d => %d\n",
i2, j2, tbl[i2][j2]);
return 0;
}

Jul 23 '05 #1
7 2432
* ma**********@ly cos.com:
[Cross-posted to C and C++ newsgroups, Not a Good Idea]
Please don't do that
(except where it is an issue of interest to practitioners of both).

Follow-up set to [comp.lang.c++].
* ma**********@ly cos.com: I am having lots of trouble getting a simple program that initializs a
dynamically allocated 2D array to work. My 2D array is not getting
initialized properly, and additionally I am getting a "Null pointer
assignment" error. Kindly help.
Don't use raw pointers.

Use standard containers like e.g. std::vector.

Then all your current problems disappear.
Also, eventually I intend to move this logic to a separate function.
For that, I believe, that I will need to pass a
pointer-to-pointer-to-pointer type as an arguent. Please confirm.
Pass a reference to the container.

[My apologies to C purists --- I am using the new operator instead of
malloc/calloc since I find its usage more intuitive]
Using 'new' is a good idea when you really need to handle allocation
yourself.

Here you _don't_ need to handle allocation yourself.

Use standard containers like e.g. std::vector.
/*************** *************** *************** *************** ************/
#include <stdio.h>

#define ROWS 3
#define COLUMNS 5
Preferentially use constants, like e.g.

std::size_t const nRows = 3;
std::size_t const nColumns = 5;

main()
Must have 'int' return value type, both in C and C++.

{
int **tbl;
Indentation.

size_t rows = ROWS;
size_t cols = COLUMNS;
Those should be 'const' (already mentioned).

int startVal = 2;

tbl = new (int**)[cols];
tbl = new (int*)[cols];

for(size_t i = 0; i < rows; i++)
tbl[i] = new (int *)[rows];
tbl[i] = new int[rows];

for(size_t i1 = 0; i1 < rows; i1++)
It's a good idea to use meaningful names, e.g. 'iRow'.

Preferentially use '++i', not 'i++'.

See
<url: http://home.no.net/dubjai/win32cpptut/html/w32cpptut_01_02 _11.html>.
<url:
http://www.parashift.c om/c++-faq-lite/operator-overloading.htm l#faq-13.11>
<url:
http://www.parashift.c om/c++-faq-lite/operator-overloading.htm l#faq-13.12>

for(size_t j1 = 0; j1 < cols; j1++)
tbl[i1][j1] = startVal++;
If you had used meaningful names this would have been

tbl[iRow][iColumn] = ++startVal;

which hopefully you can see is incorrect (which index goes where?).

for(size_t i2 = 0; i2 < rows; i2++)
for(size_t j2 = 0; j2 < cols; j2++)
printf("Row: %d, Col: %d => %d\n",
i2, j2, tbl[i2][j2]);
return 0;
}

Use standard containers like e.g. std::vector.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #2
ajk
On 30 Jan 2005 06:51:05 -0800, ma**********@ly cos.com wrote:
main()
{
int **tbl;
size_t rows = ROWS;
size_t cols = COLUMNS;
int startVal = 2;

tbl = new (int**)[cols]; // ok here allocate tbl[0..4]

for(size_t i = 0; i < rows; i++)
tbl[i] = new (int *)[rows]; // tbl[0..4] = int array [0..2] ok

for(size_t i1 = 0; i1 < rows; i1++)
for(size_t j1 = 0; j1 < cols; j1++) // now you are turning it around
tbl[i1][j1] = startVal++; // tbl[0..2][0..4] .. not good

for(size_t i2 = 0; i2 < rows; i2++)
for(size_t j2 = 0; j2 < cols; j2++)
printf("Row: %d, Col: %d => %d\n",
i2, j2, tbl[i2][j2]); // tbl[0..2][0..4] also not good.
return 0;
}


hth/ak

--
"Those are my principles. If you don't like them I have others."
Groucho Marx.
Jul 23 '05 #3
ma**********@ly cos.com wrote:
I am having lots of trouble getting a simple program that initializs a
dynamically allocated 2D array to work. My 2D array is not getting
initialized properly, and additionally I am getting a "Null pointer
assignment" error. Kindly help.
Use a matrix class ... this is just an example (although it works) -
there are some extensive matrix libraries you could use and ones that
are very efficient if the dimensions are known.

#include <vector>

template <typename w_elem_type>
class matrix
{
public:
typedef int t_Size;

t_Size m_columns;
t_Size m_rows;

std::vector<w_e lem_type> m_data;

matrix( t_Size i_columns = 0, t_Size i_rows = 0 )
: m_columns( i_columns ),
m_rows( i_rows ),
m_data( i_columns * i_rows )
{
}

w_elem_type * operator[]( t_Size i_index )
{
return & ( m_data[ i_index * m_rows ] );
}

template <typename w_Type, int w_columns, int w_rows>
matrix( const w_Type (&i_array)[w_columns][w_rows] )
: m_columns( w_columns ),
m_rows( w_rows ),
m_data( & (i_array[0][0]), & (i_array[w_columns-1][w_rows]) )
{
}

};

#include <iostream>

double array[3][4] = {
{ 1.0, 2.0, 3.3, 4.4 },
{ 1.0, 2.0, 3.3, 4.4 },
{ 1.0, 2.0, 3.3, 4.5 },

};

int main()
{
matrix<float> mat1( 3, 4 );
matrix<float> mat2;
matrix<float> mat3( array );

mat2 = mat3;

std::cout << mat2[2][3] << "\n";
}

Also, eventually I intend to move this logic to a separate function.
For that, I believe, that I will need to pass a
pointer-to-pointer-to-pointer type as an arguent. Please confirm.
If you use the martix class above, you can pass it by reference, const
reference or value.

void foo( matrix<int> & modify_me );
void foo( const matrix<int> & just_read_me );
void foo( const matrix<int> & make_a_copy_of_ me );

Note that the matrix is parameterized on element type.

[My apologies to C purists --- I am using the new operator instead of
malloc/calloc since I find its usage more intuitive]
Try not posting to the C groups if you're really interested in C++.

/*************** *************** *************** *************** ************/
#include <stdio.h>

#define ROWS 3
#define COLUMNS 5
main()
{
int **tbl;
size_t rows = ROWS;
size_t cols = COLUMNS;
int startVal = 2;

tbl = new (int**)[cols];
tbl = new (int*)[cols]; // this is probably what you wanted

for(size_t i = 0; i < rows; i++)
tbl[i] = new (int *)[rows];
tbl[i] = new (int)[rows]; // again

for(size_t i1 = 0; i1 < rows; i1++)
for(size_t j1 = 0; j1 < cols; j1++)
tbl[i1][j1] = startVal++;
tbl[j1][i1] = startVal++; // probably transposed i & j

for(size_t i2 = 0; i2 < rows; i2++)
for(size_t j2 = 0; j2 < cols; j2++)
printf("Row: %d, Col: %d => %d\n",
i2, j2, tbl[i2][j2]);
.... again transposed i and j
return 0;
}

Jul 23 '05 #4
ma**********@ly cos.com wrote:
.... snip ...
[My apologies to C purists --- I am using the new operator instead
of malloc/calloc since I find its usage more intuitive]
There is no new operator in C.
.... snip ...
main()
main returns int. Say so.
{ .... snip ...
tbl = new (int**)[cols];
see above
for(size_t i = 0; i < rows; i++)
tbl[i] = new (int *)[rows];


and see above. Try indenting your code or using a real newsreader.

In addition, do not crosspost without setting followups to one
group alone. F'ups set to the one group where it may be topical.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Jul 23 '05 #5
ma**********@ly cos.com wrote:
I am having lots of trouble getting a simple program that initializs a dynamically allocated 2D array to work. My 2D array is not getting
initialized properly, and additionally I am getting a "Null pointer
assignment" error. Kindly help. #include <stdio.h>

#define ROWS 3
#define COLUMNS 5

main()
{
int **tbl;
size_t rows = ROWS;
size_t cols = COLUMNS;
int startVal = 2;

tbl = new (int**)[cols];
Bizarre that I had never seen someone do this until yesterday,
but now I've seen it twice (it came up in another thread).
What you mean is:

.. tbl = new int*[cols];

tbl is a pointer to pointer to int. So you must create
pointer(s) to int for it to point at.

The syntax you wrote is actually illegal (Comeau C++ would have
told you that). But some compilers parse it as:

.. tbl = (new (int**))[cols]

ie. creating a new pointer to pointer to int, and then
dereferencing it (causing undefined behaviour, probably
the cause of the errors you reported).

For more information, see the thread in comp.std.c++
titled "Strange new/new() problem".

for(size_t i = 0; i < rows; i++)
tbl[i] = new (int *)[rows];
Ditto: tbl[i] = new int[rows];

tbl[i] is a pointer to int. It points to ints.
Obviously, trying to point it to a pointer-to-int will
get you into trouble.
for(size_t i1 = 0; i1 < rows; i1++)
for(size_t j1 = 0; j1 < cols; j1++)
tbl[i1][j1] = startVal++;
That should be tbl[j1][i1]

Remember that you created 'cols' pointers to int, and
each one points to a block of 'rows' ints.
for(size_t i2 = 0; i2 < rows; i2++)
for(size_t j2 = 0; j2 < cols; j2++)
printf("Row: %d, Col: %d => %d\n",
i2, j2, tbl[i2][j2]);
Ditto.
return 0;
You should delete[] all of the stuff you allocated.
}


You could have saved yourself a lot of trouble by using
a vector of vectors, instead of new and delete.

Jul 23 '05 #6
On Sun, 30 Jan 2005 15:15:20 GMT, al***@start.no (Alf P. Steinbach)
wrote:
* ma**********@ly cos.com:
[Cross-posted to C and C++ newsgroups, Not a Good Idea]


Please don't do that
(except where it is an issue of interest to practitioners of both).

Follow-up set to [comp.lang.c++].

Actually they weren't. (I've made the same mistake in the past, it's
not as convenient with Agent as one might like.) <G>

<snip>
main()


Must have 'int' return value type, both in C and C++.

In C99, and (any) C++.

<snip>
tbl = new (int**)[cols];


tbl = new (int*)[cols];

No, that's also a (somewhat more obscure) mistake. It parses as
tbl = ( new (int*) ) [cols]
which allocates a single pointer, uninitialized, and tries to
subscript it. Except in (some versions of?) g++, which "fixes" it for
you. To be standard you want
tbl = new int * [cols];

<snip>

- David.Thompson1 at worldnet.att.ne t
Jul 23 '05 #7
main()
{
int **tbl;
size_t rows = ROWS;
size_t cols = COLUMNS;
int startVal = 2;

tbl = new (int**)[cols]; // ok here allocate tbl[0..4]

for(size_t i = 0; i < cols; i++) //here is simple prob u are allocating for cols and accessing till row??????tbl[i] = new (int *)[rows]; // tbl[0..4] = int array [0..2] ok
for(size_t i1 = 0; i1 < rows; i1++)
for(size_t j1 = 0; j1 < cols; j1++) // now you are turning it around
tbl[i1][j1] = startVal++; // tbl[0..2][0..4] .. not good

for(size_t i2 = 0; i2 < rows; i2++)
for(size_t j2 = 0; j2 < cols; j2++)
printf("Row: %d, Col: %d => %d\n",
i2, j2, tbl[i2][j2]); // tbl[0..2][0..4] also not good.
return 0;
}


Jul 23 '05 #8

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

Similar topics

5
2308
by: Rob Ristroph | last post by:
Hi, It's pretty unhelpful to post "I have a huge piece of code that crashes in strange places, what's the problem?" but that's basically my problem and I really am at my wit's end. The piece of code in question always crashes in an STL operation such as a vector.push_back, but the location of the crash changes as I change how various parts are handled in memory, i.e., make some things dynamically allocated instead of new'd. I know...
4
1725
by: stephenma7 | last post by:
Hi, everybody. I am new here. I have encountered these many problems for the last couple of days. I have Linux Fedora Core 3(Gnu G++ 3.4.2), Linux Fedora Core 2 (Gnu G++ 3.3.3), Red Hat 9 (Gnu G++ 3.2.2, this is dual processors). I have the same set of programs that I wrote and when I ran on the three machines, which have different amount of memories, processors' speeds, and settings. I got three different seg faults at different...
4
431
by: masood.iqbal | last post by:
I am having lots of trouble getting a simple program that initializs a dynamically allocated 2D array to work. My 2D array is not getting initialized properly, and additionally I am getting a "Null pointer assignment" error. Kindly help. Also, eventually I intend to move this logic to a separate function. For that, I believe, that I will need to pass a pointer-to-pointer-to-pointer type as an arguent. Please confirm.
7
4062
by: nk | last post by:
Hi, I'm a newbie on this language. I would be very happy if you help me about the following issue: The code below, reads some names(strings), stores them, and stores the addresses in the pointer array, and writes them out. But it fails and exits the program. I guess that it's about initializing the array but i couldn't find a way to make it ok....
13
2275
by: John | last post by:
Is this a valid C++ program that will not crash on any machine? #include <iostream> using namespace std; int main( void ) { int i; cin >i; double X; X = 1123;
4
6344
by: wyrmmage | last post by:
hello :) I need to make a dynamically allocated array of pointers, using a .hpp and .cpp file; how do I accomplish this? I think I know how to make an array of pointers, and I know how to make a dynamically allocated array, but I am lost as to how to put the two together... Any help would be appreciated :) -wyrmmage
4
1771
by: attackwarningred | last post by:
Dear All, Hello! I've just started to use Python and its a lovely language! I've previously programmed in Fortran 95 and have just began to use numpy. I'm having a few problems with arrays in Python though and wondered if someone could offer me some advice? I wrote the following Fortran code to randomly generate numbers from a log-normal distribution for use in a Monte Carlo model: do n=1,shotcount F(n)=G05DEF(F_mean,F_sd)
2
3049
by: Pavan | last post by:
Hi, I need to create a consant array of larze size but however its elements can be calculated using an equation, say for example I need an int arry of 20 elements where each element will be arr = 2 + (i*i) But I want arry to be constant. How can I declare such a constant array without actually defining all the elements?
14
1705
by: stevenruiz | last post by:
Hello All My question mainly is how to use/reference Double Pointers? I am currently trying to understand what the meaning of a 'vector of pointers' means also? What I am trying to do is take a char array and break it up into words omitting the spaces. What needs to be noted is that I am trying to accomplish this only using char ** and char *. Therefore, I am creating it from scratch. Below is code that I have written so far:
0
8821
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
8718
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
9196
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
9047
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
7973
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
6646
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
5967
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
4477
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
3175
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

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.