473,396 Members | 1,990 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,396 software developers and data experts.

2D Array not working

Hi everybody,

in the sample below my programm gives a "Bus error" on the marked line.
I don't get it why that happens. I followed the instructions in the
C-FAQ.

#include <math.h>
#include <stdlib.h>

#define dim 2
#define length 3

int main (int argc, const char * argv[]) {
int i,j;
int volume=(int)pow(length,dim);

int **nbrs = (int **) malloc(volume * sizeof(int *));
for (i=0; i<volume; i++)
*(nbrs+i) = (int *) malloc(2*dim * sizeof(int));

for (i=0;i<volume;i++)
for(j=0;j<(2*dim);j++) {
*(nbrs+i)=i;
*(*(nbrs+i)+j)=j; //here is the problem
}

for (i=0; i<volume; i++)
printf("%d\n", nbrs[i]);

return 0;
}

Feb 5 '07 #1
5 1648
On 5 Feb, 15:28, Jonathan Groß <pge03...@studserv.uni-leipzig.de>
wrote:
Hi everybody,

in the sample below my programm gives a "Bus error" on the marked line.
I don't get it why that happens. I followed the instructions in the
C-FAQ.
God only knows what you are trying to achieve here. It would be nice
to have a short description...
#include <math.h>
#include <stdlib.h>
#include <stdio.h /* so we've got the printf functions prototype
in scope */
#define dim 2
#define length 3

int main (int argc, const char * argv[]) {
int i,j;
int volume=(int)pow(length,dim);
On this occasion, you got away with it, but do you believe this will
always work?
int **nbrs = (int **) malloc(volume * sizeof(int *));
for (i=0; i<volume; i++)
*(nbrs+i) = (int *) malloc(2*dim * sizeof(int));
So you've filled the first array with pointers to storage...
for (i=0;i<volume;i++)
for(j=0;j<(2*dim);j++) {
*(nbrs+i)=i;
So now you repeatedly overwrite those pointers with an integer value.
*(*(nbrs+i)+j)=j; //here is the problem
And expect to dereference that value... (BTW, please use /*...*/ for
comments as they are much better handled when cut and pasted from
newgroup articles).
}

for (i=0; i<volume; i++)
printf("%d\n", nbrs[i]);

return 0;

}

Feb 5 '07 #2
Jonathan Groß <pg******@studserv.uni-leipzig.dewrites:
Hi everybody,

in the sample below my programm gives a "Bus error" on the marked
line.
You either need to turn up the warning level on your compiler or you
need to listen to it! You destroy a correctly set up pointer by
assigning an integer value to it. Trouble is inevitable after that.

BTW, you don't have a 2D array. You have an array of pointers to
arrays of integers. C does have 2D arrays and they work differently.
I don't get it why that happens. I followed the instructions in
the C-FAQ.

#include <math.h>
#include <stdlib.h>
You need <stdio.hfor printf. Did your compiler not tell you this?
#define dim 2
#define length 3

int main (int argc, const char * argv[]) {
int i,j;
int volume=(int)pow(length,dim);

int **nbrs = (int **) malloc(volume * sizeof(int *));
There is no need to cast the return value from malloc. The preferred
idiom is:

int **nbrs = malloc(volume * sizeof *nbrs);
for (i=0; i<volume; i++)
*(nbrs+i) = (int *) malloc(2*dim * sizeof(int));
I would write:
nbrs[i] = malloc(2 * dim * sizeof *nbrs[i]);

Array access is simpler using [] rather than * and +.
>
for (i=0;i<volume;i++)
for(j=0;j<(2*dim);j++) {
*(nbrs+i)=i;
Your problem is really here, not on the line below. *(nbrs+i) is the
same as nbrs[i] which is a pointer to some ints. You correctly set it
up a few lines above. Putting i into it is illegal C. I can't
correct it because I have no idea what you intended to do here.
*(*(nbrs+i)+j)=j; //here is the problem
nbrs[i][j] = j is a much simpler way to write this.
}

for (i=0; i<volume; i++)
printf("%d\n", nbrs[i]);
%d needs and int. nbrs[i] is an int *. What did you want to do here?
Maybe you intended to have another loop and print nbrs[i][j].
return 0;
}
--
Ben.
Feb 5 '07 #3
Jonathan Groß wrote, On 05/02/07 15:28:
Hi everybody,

in the sample below my programm gives a "Bus error" on the marked line.
I don't get it why that happens. I followed the instructions in the C-FAQ.
Not very well though.
#include <math.h>
#include <stdlib.h>

#define dim 2
#define length 3
Macros are traditionally all upper case, going against this convention
makes it harder for those used to it, i.e. most C programmers.
int main (int argc, const char * argv[]) {
int i,j;
int volume=(int)pow(length,dim);
You don't need the cast, it will behave exactly the same without it.
Also, without a good reason I'm not convinced that using a floating
point function is the best way to generate an array size.
int **nbrs = (int **) malloc(volume * sizeof(int *));
Does the C FAQ really use all these horrible and needless casts.
<check/>
No, it doesn't. Why do the extra typing when it is just more to get
wrong and can even hide two different problems. Also, as the C FAQ notes
in a footnote, there is a better way to use sizeof.
int **nbrs = malloc(volume * sizeof *nbrs);
About 10 fewer characters to type and less error prone.

Also, as the FAQ notes, you should check the return value of malloc.
for (i=0; i<volume; i++)
*(nbrs+i) = (int *) malloc(2*dim * sizeof(int));
Same comments as before, aditionally I would use array is easier to read
(in my opinion) in this case.
nbrs[i] = malloc(2*dim * sizeof *nbrs[i]);
for (i=0;i<volume;i++)
for(j=0;j<(2*dim);j++) {
*(nbrs+i)=i;
*(*(nbrs+i)+j)=j; //here is the problem
Again, array notation makes it easier to read.
nbrs[i]=i;
nbrs[i][j]=j;

Now look at the first of these two lines and compare it to the loop
allocating the space for the rows. You should see that you are
overwriting all those pointers you were so careful to allocate. Your
compiler should even have complained about the assignment "*(nbrs+i)=i"
to let you know it is a problem. Whether the problem is that you want
something other than a 2D array or whether you don't understand pointers
to pointers or what is hard to say at this point.
}

for (i=0; i<volume; i++)
printf("%d\n", nbrs[i]);
This loop also does not make sense.
return 0;
}
--
Flash Gordon
Feb 5 '07 #4
On Mon, 5 Feb 2007 16:28:18 +0100, Jonathan Groß
<pg******@studserv.uni-leipzig.dewrote:
>Hi everybody,

in the sample below my programm gives a "Bus error" on the marked line.
I don't get it why that happens. I followed the instructions in the
C-FAQ.

#include <math.h>
#include <stdlib.h>

#define dim 2
#define length 3

int main (int argc, const char * argv[]) {
Others have given you good advice about your problems.

I would add that you do not use either argc or argv in your code, so a
better definition to use for main() would be:

int main(void)

The C standard allows this definition, and maybe even yours [1]:

<quote>
5.1.2.2.1 Program startup

The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any
names may be used, as they are local to the function in which they are
declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.
</quote>

[snip]

Best regards
--
jay

[1]
Does the C standard allow the OP's additional qualification of const
to the second argument to main()? In other words, is:

int main (int argc, const char * argv[])

an acceptable definition for main(), when, strictly speaking, it
should be:

int main(int argc, char *argv[])

I suspect so, since the former is basically more restrictive about
what you can "do" with the second argument, and poses no harm in
placing such a restriction.
Feb 6 '07 #5
Jonathan Groß:
Hi everybody,

in the sample below my programm gives a "Bus error" on the marked line.
I don't get it why that happens. I followed the instructions in the
C-FAQ.

#include <math.h>
#include <stdlib.h>

#define dim 2
#define length 3

Most people think it's a good idea to use capital letters for macro names.

int main (int argc, const char * argv[]) {
int i,j;
int volume=(int)pow(length,dim);

The cast is redundant from a Standard C point of view, but it may serve to
suppress a compiler warning.

It's also a good idea to use "const" whenever possible, e.g.:

int const volume = (int)pow(length,dim);

int **nbrs = (int **) malloc(volume * sizeof(int *));

This cast serves no purpose. In fact, it:

a) Makes the code look messy
b) Could potentially hide the error of neglecting to include stdlib.h

A better solution would be:

int **const nbrs = malloc(volume * sizeof*nbrs);

for (i=0; i<volume; i++)
*(nbrs+i) = (int *) malloc(2*dim * sizeof(int));

Replace *(nbrs+i) with nbrs[i], it's neater that way:

for(i=0;i!=volume;++i) nbrs[i] = malloc(2*dim*sizeof**nbrs);

Or alternatively, you could loop through it with a pointer:

int const **p = nbrs;
int const *const *const pover = nbrs + volume;

do *p++ = malloc(2*dim*sizeof**pp);
while (pover!=p);

for (i=0;i<volume;i++)
for(j=0;j<(2*dim);j++) {
*(nbrs+i)=i;
*(*(nbrs+i)+j)=j; //here is the problem
}

If the *(nbrs+i)=i; line compiles then you might wanna pick up another
compiler. You should get a type mismatch. The thing on the left is an int*,
while the thing on the right is an int.

You think you're working with a two-dimensional array (i.e. an array of
arrays), when in actual fact you're working with an array of pointers to
arrays.

for (i=0; i<volume; i++)
printf("%d\n", nbrs[i]);

return 0;
}
--
~/JB\~
Feb 7 '07 #6

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

Similar topics

12
by: Treetop | last post by:
I cannot get this array to work. I want to have the game listed until the day after the event, then come off the list. function events() { var today = new Date(); var dayarray=new...
22
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last...
35
by: VK | last post by:
Whatever you wanted to know about it but always were affraid to ask. <http://www.geocities.com/schools_ring/ArrayAndHash.html>
7
by: ritchie | last post by:
Hi all, I am new to this group and I have question that you may be able to help me with. I am trying to learn C but am currently stuck on this. First of all, I have a function for each sort...
8
by: intrepid_dw | last post by:
Hello, all. I've created a C# dll that contains, among other things, two functions dealing with byte arrays. The first is a function that returns a byte array, and the other is intended to...
8
by: ulyses | last post by:
I'm trying to put pointer to flexible array of structures in other structure. I want to have pointer to array of pixels in screen structure. Here is mine code, but I think it isn't quite all right:...
29
by: yourmycaffiene | last post by:
Okay, this if my first post so go easy on me plus I've only been using C for a couple of weeks. I'm working on a program currently that requires me to read data from a .dat file into a 2d array and...
9
by: Miro | last post by:
VB 2003 at the end of the code, this works great. bytCommand = Encoding.ASCII.GetBytes("testing hello send text") udpClient.Send(bytCommand, bytCommand.Length) and this recieves it Dim...
29
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to...
9
by: JackpipE | last post by:
I need to create multidimensional array with arrays inside of it. database name | value1 | value2 john | red | 45 john | red | 56 john | yellow | 11 mike | blue | 23 mike | black | 41
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.