Arrays in C

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 1412 Views - Last Post: 18 August 2009 - 12:39 PM Rate Topic: -----

#1 dr_spitfire  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 99
  • Joined: 13-August 09

Arrays in C

Posted 13 August 2009 - 03:50 PM

Quick question, I am working on a project in which I will be passed a series of data (currently from a file that I have it rip apart and interpret)

It's a graphical program so what it does is the file I'm using right now to test it contains a series of 4 triangles separated into sets of 3 points in 3d space and then it maps it out and that works and to do so I've been using an array to hold the data after it's interpreted as such:

float place2Be[3][3][4] 

and that works for this simple object I'm using right now however the goal is to eventually get to a big scary object of unknown sides composed of triangles...

So in an ideal world I could do something like:
int someVariable=4;
float place2Be[3][3][someVariable];

and then later after i tested that have the value of someVariable change based on the size of the data I'm being passed... obviously though, this isn't an ideal world because that doesn't work (I didn't think it would but I tried any ways in hopes that I could save myself hours and hair)

Is there some way however to produce a similar effect? or maybe I don't know some secret :ph34r: way to do that? any help or directions to some wise guru at the top of the mountain who could help would be greatly appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Arrays in C

#2 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: Arrays in C

Posted 13 August 2009 - 06:02 PM

3d array? Never heard of it. But I have used 2d arrays. Just not in C.

This post has been edited by OliveOyl3471: 13 August 2009 - 07:50 PM

Was This Post Helpful? 0
  • +
  • -

#3 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Arrays in C

Posted 13 August 2009 - 06:22 PM

Any chance we could trade that 3D array in for a cleaner data structure? I don't like 2D arrays, I really don't like 3D arrays. :)
Was This Post Helpful? 0
  • +
  • -

#4 redhotfire0  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 210
  • Joined: 13-July 09

Re: Arrays in C

Posted 13 August 2009 - 09:36 PM

You can first try:
place2Be[][]


And then later find the size of the array. But, I could be wrong.

Red
Was This Post Helpful? 0
  • +
  • -

#5 redkid  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 32
  • Joined: 23-April 09

Re: Arrays in C

Posted 14 August 2009 - 03:59 AM

It is possible to use calloc or malloc to make dynamic 2D arrays and surely, 3D arrays. Hopefully this is what you're looking for:
#include <stdio.h>
#include <stdlib.h>

int
main (void)
{
	int nrows, ncols, i, j;
	int **numbers;
	
	printf ("How many rows and columns?> ");
	scanf ("%d%d", &nrows, &ncols);

	numbers = (int **) calloc (nrows, sizeof(int *));

	for (i=0; i<ncols; i++)
		numbers[i] = (int *) calloc (ncols, sizeof(int));

	for (i=0; i<nrows; i=i++)
	{	
		for (j=0; j<ncols; j=j++)
		{
			printf ("%3d ", numbers[i][j]);
			
		}
		printf ("\n");
	}

	for (i=0; i<ncols; ++i)
		free (numbers[i]);

	free (numbers);

	return (0);
}


This post has been edited by redkid: 14 August 2009 - 04:07 AM

Was This Post Helpful? 1
  • +
  • -

#6 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • View blog
  • Posts: 2,339
  • Joined: 20-August 07

Re: Arrays in C

Posted 14 August 2009 - 04:02 AM

How about breaking this problem up into a struct to store your 3D Coordinates rather than an iffy array-based solution
typedef struct
{
    int x, y, z;
} point3D; 

You can then make an array using the struct - this ought to clean up the problem a little bit.

This post has been edited by Bench: 14 August 2009 - 04:06 AM

Was This Post Helpful? 0
  • +
  • -

#7 redkid  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 32
  • Joined: 23-April 09

Re: Arrays in C

Posted 14 August 2009 - 04:28 AM

View PostBench, on 14 Aug, 2009 - 03:02 AM, said:

How about breaking this problem up into a struct to store your 3D Coordinates rather than an iffy array-based solution
typedef struct
{
    int x, y, z;
} point3D; 

You can then make an array using the struct - this ought to clean up the problem a little bit.

I second that.
Was This Post Helpful? 0
  • +
  • -

#8 aluminumstudios  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-August 09

Re: Arrays in C

Posted 14 August 2009 - 06:07 AM

I am a novice, just refreshing my 10 year outdated skills, but I recently wanted to use 3d arrays and quickly gave up because I saw that they seem difficult to allocate dynamically. I used an array of structs, but for my 2D arrays I did this.

Instead of array[x][y] I created a one-dimensional array of size maximum_possible_x*maximum_possible_y and address it as array[y*maximum_possible_y+x] (in this case it is x,y coordinates in a 2d image.)

I am thinking, that this might work for a 3D array as well ...

If you want place2be[x][y][z] and you know the max size of x,y,z make a one-dimensional array of size maximum_x*maximum_y*maximum_z.

Then you can logically "break it up" into sections by addressing it like this.

place2be[2][6][18] would be addressed as place2be[max_x*2+max_y*6+18]

At least I *think* this would work for 3D arrays.

Please forgive me if my logical is totally wrong, I've been out in the heat all day ^_^;
Was This Post Helpful? 0
  • +
  • -

#9 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5823
  • View blog
  • Posts: 12,675
  • Joined: 16-October 07

Re: Arrays in C

Posted 14 August 2009 - 09:04 AM

View Postaluminumstudios, on 14 Aug, 2009 - 07:07 AM, said:

array[y*maximum_possible_y+x] (in this case it is x,y coordinates in a 2d image.)


Actually, it should be array[x*maximum_possible_y+y], or vice versa; the one coordinate is jumping over the block of the other. This is pretty much the way I do multidimensional arrays as well. While a 3d array is limited use and I concur with the use of a point struct, it sounded like too much fun not to try.

Adapting some 2d code I had, I came up with this:
#include <stdlib.h>
#include <stdio.h>

typedef enum BOOL { false, true } bool;

#define UINT unsigned int

typedef int BoxValueType;

typedef struct {
	UINT dx, dy, dz, size;
	BoxValueType *data;
} Box;


void boxCreate(Box *box, UINT dx, UINT dy, UINT dz) {
	box->dx = dx;
	box->dy = dy;
	box->dz = dz;
	box->size = dx*dy*dz;
	box->data = malloc(box->size * sizeof(BoxValueType));
}

void boxDestroy(Box *box) { free(box->data); }

BoxValueType *boxGetCell(Box *b, UINT x, UINT y, UINT z) {
	if (x<b->dx && y<b->dy && z<b->dz) {
		UINT index = z;
		index += (y*b->dz);
		index += (x*b->dy*b->dz);
		return &(b->data[index]);
	}
	return NULL;
}

BoxValueType boxGet(Box *b, UINT x, UINT y, UINT z, BoxValueType defaultValue) {
	BoxValueType *cell = boxGetCell(b, x, y, z);
	return (cell==NULL) ? defaultValue : *cell;
}

bool boxSet(Box *b, UINT x, UINT y, UINT z, BoxValueType value) {
	BoxValueType *cell = boxGetCell(b, x, y, z);
	if (cell!=NULL) { *cell = value; }
	return (cell!=NULL);
}

void boxPrint(Box *b ) {
	int x,y,z;
	for(z=0; z<b->dz; z++) {
		for(y=0; y<b->dy; y++) {
			for(x=0; x<b->dx; x++) { printf("%d ", boxGet(b,x,y,z,-1)); }
			printf("\n");
		}
		printf("------------------------\n");
	}
}

void testLoad(Box *b ) {
	int x,y,z, i=0;
	
	for(z=0; z<b->dz; z++) {
		for(y=0; y<b->dy; y++) {
			for(x=0; x<b->dx; x++) { boxSet(b,x,y,z,++i); }
		}
	}
}


int main() {
	Box box;
	
	boxCreate(&box, 5, 6, 2);
	testLoad(&box);
	boxPrint(&box);
	boxDestroy(&box);
	
	return 0;
}



There are more methods, like passing a function pointer to the looping function, but this seemed easier to show.

Note the use of BoxValueType. Live code would choose it's own value for this, so you can put anything in the bucket. This is a C style template. For max modularity you'd use void pointers for the data type, but that can be hard to follow too.

Edit: bloody B) smilie.

This post has been edited by baavgai: 14 August 2009 - 09:05 AM

Was This Post Helpful? 0
  • +
  • -

#10 dr_spitfire  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 99
  • Joined: 13-August 09

Re: Arrays in C

Posted 14 August 2009 - 11:22 AM

I'll look into the code you guys posted (just sat down and skimmed over it) thanks for the replies!

As for using a struct... I'm a pretty much nublet here (getting to work on this project was a bit of a fluke having to do with the fact that the person who came before me had even LESS experience so it looked like I was amazing by comparison) but my point is I'm completely unfamiliar with the concept is there a link or something that you could post me that would give me an easy to understand overview so I can see if I can use that easily...

The reason I picked 3d arrays is because it seemed like they were built for this... because I need not only a list of points but I need them arranged in a specific order (was going to use 2d Array but openGL freaks out on you if your points aren't done counterclockwise and it won't always be obvious which points connect to which)

as it's set up now the third parameter refers to which triangle in the set, the first to which point of the 3 and the second to x,y, or z coord for that individual point

example
place2Be[0][0][0] refers to the x coord of the first point in the first triangle
place2Be[2][1][3] refers to the y coord of the third point of the 4th triangle

However this is an internship and I'm still at school so I want to learn more stuff anyway so even if I don't end up changing it (later on down the road my program may become the subroutine of another program which passes a 3d array so it would make little sense to change then but still) anyway yeah either way I would like to know more about structs... (specially if I can't get this calloc/malloc stuff working)
Was This Post Helpful? 0
  • +
  • -

#11 dr_spitfire  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 99
  • Joined: 13-August 09

Re: Arrays in C

Posted 14 August 2009 - 12:46 PM

ok sorry to be so wordy and such as much as a lot of this is probably way over my head I'm completely entranced by all this code floating by... anyway

redkid I was looking over your first post and that looked like it was right up my alley for what I wanted to do, but since your example was with a 2d array of unknown sides and I only have one unknown side but a 3d array (it wasn't immediately obvious to me how to make the jump from 2d to 3d) I did a quick google search and found the following which looked promising: (this is where everyone can join in :D)

Quote

Finally, you can use pointers-to-arrays:

int (*array4)[NCOLUMNS] =
(int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));

, but the syntax gets horrific and all but one dimension must be known at compile time.



I know all but one dimension so in my attempt to interpret what was on the screen I tried to adapt that to something I could work with...

so if anyone understood that, in the case of a 3d array would that look like:

int (*place2Be)[3][3] = (int (*)[3])malloc(nrows * sizeof(*place2Be));

or am I way off?

or if I go back to your example red for my purposes would this be how I modify it?:
#include <stdio.h>
#include <stdlib.h>

int
main (void)
{
	int nrows, ncols, ntriangles, i, j, k;
	int ***numbers;
   
	printf ("How many triangles?> ");
	scanf ("%d", &ntriangles);
	nrows = 3;
	ncols = 3;

	numbers = (int ***) calloc (nrows, sizeof(int **));

	for (i=0; i<ncols; i++)
		numbers[i] = (int **) calloc (ncols, sizeof(int *));
		
	for (j=0; j<rows; j++)
		{
		for (k=0; j<ncols;j++
			 numbers[j][k]= (int *)calloc (ntriangles, sizeof(int));
		 }


   for (k=0; k<ntriangles; k=k++)
	{
	for (i=0; i<nrows; i=i++)
	{	
		for (j=0; j<ncols; j=j++)
		{
			printf ("%3d ", numbers[i][j]);
		   
		}
		printf ("\n");
	}
	printf("\n");
	}

	for (j=0; j<nrows; ++j)
	{
	for (k=0; k<ncols; ++k)
		free (numbers[j][k]);
	}

	for (i=0; i<nrows; ++i)
		free (numbers[i]);

	free (numbers);

	return (0);
}


or am I just way off?
Was This Post Helpful? 0
  • +
  • -

#12 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5823
  • View blog
  • Posts: 12,675
  • Joined: 16-October 07

Re: Arrays in C

Posted 14 August 2009 - 02:14 PM

View Postdr_spitfire, on 14 Aug, 2009 - 12:22 PM, said:

place2Be[0][0][0] refers to the x coord of the first point in the first triangle
place2Be[2][1][3] refers to the y coord of the third point of the 4th triangle


No, no, NO, for love of God, no. Magic values are so bad in so many ways. That you had to describe the need for the 3d array only emphasizes why it's bad.

You have a collection of triangles. Triangles consist of three points. Those points consist of x and y. The code should describe with, explicitly and clearly. A single array of struct will do this.

e.g.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
	int x, y;
} Point;

typedef struct {
	Point pt[3];
} Triangle;

typedef struct {
	int size;
	Triangle *items;
} Triangles;


void initTriangles(Triangles *ts, int ntriangles) {
	ts->size = ntriangles;
	ts->items = calloc(ts->size, sizeof(Triangle));
}

void destroyTriangles(Triangles *ts) {
	free (ts->items);
}

void printTriangles(Triangles *ts) {
	int i, j, k;
	for (i=0; i<ts->size; i++) {
		Triangle *item = &ts->items[i];
		printf ("%d: ", i);
		for (j=0; j<3; j++) {
			Point *pt = &item->pt[j];
			printf ("(%d,%d) ", pt->x, pt->y);
		}
		printf ("\n");
	}
}

int main () {
	Triangles triangles;
	
	initTriangles(&triangles, 5);
	printTriangles(&triangles);
	destroyTriangles(&triangles);

	return 0;
}



Do be clear, if you decided your triangle existed in 3D space you'd only have to add a z to Point. A 3D array would fail for your needs entirely. Don't use them. Probably ever.

This post has been edited by baavgai: 14 August 2009 - 02:15 PM

Was This Post Helpful? 1
  • +
  • -

#13 dr_spitfire  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 99
  • Joined: 13-August 09

Re: Arrays in C

Posted 14 August 2009 - 03:42 PM

View Postbaavgai, on 14 Aug, 2009 - 01:14 PM, said:

No, no, NO, for love of God, no. Magic values are so bad in so many ways. That you had to describe the need for the 3d array only emphasizes why it's bad.


*cowers in corner*

ok ok so no 3d array!

Ok, do you know a site that breaks down structs for people who've never seen one?
Your code looks easy enough but last time I said that when someone provided help I found out later I hadn't completely understood all of that concept and I had errors like crazy until I learned properly... I've got the weekend to read up though before I have to go trying to implement it and I'd rather learn how it works properly than blindly copy code anyways!

(As I said I haven't had that much exposure to C but I got hired to replace someone who'd had NO exposure to C so they've kind of left me to my own devices to try and learn it)

Thanks for the reply! maybe soon I won't have to be such a n00b >.<
Was This Post Helpful? 0
  • +
  • -

#14 redkid  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 32
  • Joined: 23-April 09

Re: Arrays in C

Posted 14 August 2009 - 05:21 PM

View Postdr_spitfire, on 14 Aug, 2009 - 02:42 PM, said:

View Postbaavgai, on 14 Aug, 2009 - 01:14 PM, said:

No, no, NO, for love of God, no. Magic values are so bad in so many ways. That you had to describe the need for the 3d array only emphasizes why it's bad.


*cowers in corner*

ok ok so no 3d array!

Ok, do you know a site that breaks down structs for people who've never seen one?
Your code looks easy enough but last time I said that when someone provided help I found out later I hadn't completely understood all of that concept and I had errors like crazy until I learned properly... I've got the weekend to read up though before I have to go trying to implement it and I'd rather learn how it works properly than blindly copy code anyways!

(As I said I haven't had that much exposure to C but I got hired to replace someone who'd had NO exposure to C so they've kind of left me to my own devices to try and learn it)

Thanks for the reply! maybe soon I won't have to be such a n00b >.<

I had a similar experience with C# but know this, Google is your best friend. (And MSDN for C#).

So anyway, here's what I got in Google: http://www.google.co...s...es+&aqi=g10

Also do as the other experts are saying, they are right to suggest structures, they will make life so much easier.

This post has been edited by redkid: 14 August 2009 - 05:23 PM

Was This Post Helpful? 0
  • +
  • -

#15 dr_spitfire  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 99
  • Joined: 13-August 09

Re: Arrays in C

Posted 14 August 2009 - 05:32 PM

View Postredkid, on 14 Aug, 2009 - 04:21 PM, said:

I had a similar experience with C# but know this, Google is your best friend. (And MSDN for C#).

So anyway, here's what I got in Google: http://www.google.co...s...es+&aqi=g10

Also do as the other experts are saying, they are right to suggest structures, they will make life so much easier.


Yeah I'm unhappy that I may need to rework the whole project (but tbh with the sloppy coding the 2 of us who worked together threw in there I may have needed to anyway since we both didn't know what we were doing) but I will look into doing it that way...

I just wanted to know if there was a particular site anyone would recommend to learn that type of thing...

google hasn't been kind to me over the course of the week (lot of c++ and c# answers which don't always help) but that may be because as I said I've been a bit in over my head and frustrated... anyway (I say that too much I noticed) I'm going to look into structures and read up and hopefully I'll be an expert on them by monday and after tapping away at my keyboard for hours... well who am I kidding there'll be something else wrong I need to fix but if there weren't and it all magically worked on monday I'd be out of an internship position so I'm not complaining :P
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2