473,804 Members | 2,141 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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*di m);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 1666
On 5 Feb, 15:28, Jonathan Groß <pge03...@studs erv.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*di m);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******@studs erv.uni-leipzig.dewrite s:
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*di m);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*di m);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******@studs erv.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!=volu me;++i) nbrs[i] = malloc(2*dim*si zeof**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*si zeof**pp);
while (pover!=p);

for (i=0;i<volume;i ++)
for(j=0;j<(2*di m);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
2429
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 Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat") var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec
22
4656
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 month I had enough of extra proof that the cat doesn't hount mice anymore in more and more situations. And the surrent sicretisme among array and hash is the base for it. I summarized all points in this article:...
35
6683
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
25175
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 (Bubble, insertion, selection..). I have an array of int's and am passing them to each sort function.
8
10722
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 receive a byte array as one of its parameters. The project is marked for COM interop, and that all proceeds normally. When I reference the type library in the VB6 project, and write the code to call the function that returns the byte array, it works
8
2474
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: struct pixel { int x; int y; int color; };
29
10454
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 then print out the contents of the 2d array to the screen. I wil also need to append data to the .dat file but mostly right now I'm worrying about getting the info into the 2d array. My .dat file looks like this 1 20000 2 30000 3 40000
9
4937
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 strReturnData As String = _ System.Text.Encoding.ASCII.GetString(receiveBytes)
29
4259
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 a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could set there values to null and remove them afterwards? Thanks, Jon
9
1912
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
9594
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
10350
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...
1
10351
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7638
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
5534
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...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4311
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
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
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.