GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 09-Feb-2009, 21:48
mas287 mas287 is offline
New Member
 
Join Date: Jun 2008
Posts: 9
mas287 is on a distinguished road

Dynamic 2 dimensional array problem


Hi,

My existing code is like this :

CPP / C++ / C Code:

typedef struct node
{
  int nom;
  float salary;
  struct node *p;
} NODE;

NODE *check[100][100];

main()
{

NODE *q; 

funcA (); // set value for check

q=check[i][j];

funcB() ; //do something with q


}


If you can see that, the above code use static dimentional array for check. Do you have any idea about how to make/ declare check as a dynamic dimensional array ?

Many thanks.
  #2  
Old 09-Feb-2009, 22:52
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 841
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: Dynamic 2 dimensional array problem


If I'm not mistaken
CPP / C++ / C Code:
NODE *check[100][100];
is an array of 100 arrays of 100 each - POINTERS to type NODE.
I don't think that is what you intended.
I don't think you want a block of space to store 100 arrays of 100 struct nodes either.

Nope, structs like you show above are intended to be used in a "self referencing data structure" which is more often referred to as a "Linked List". For that you will want to do one allocation for each new node. You would use malloc() or calloc() for each allocation.

The idea is to form a chain of nodes stored at different locations in memory and be able to access any of them by having each linked to the next simply by having each 'know' the address of the next. That is done by storing that address in the
CPP / C++ / C Code:
struct node *p;
member of each node.

There have been several good threads on this in the past couple of years.
Use the "Search this Forum" link at the top-right of the main forum page.
  #3  
Old 10-Feb-2009, 05:26
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 335
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Dynamic 2 dimensional array problem


Quote:
Originally Posted by mas287
If you can see that, the above code use static dimensional array for check. Do you have any idea about how to make/ declare check as a dynamic dimensional array ?

Something like this:

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef __cplusplus
typedef char bool;
#endif

#ifndef TRUE
#define TRUE	(1)
#define FALSE	(0)
#endif

typedef struct node
{
    float f;
    struct node* next;
} NODE;

typedef struct list
{
    NODE* head;
} LIST;

bool list_add_node(LIST* pList, const float f)
{
    bool success = FALSE;
    NODE* n = NULL;
    NODE* p = (NODE*)malloc(sizeof(NODE));
    if(p != NULL)
    {
	p->f = f;
	p->next = NULL;
	if(pList != NULL)
	{
	    n = pList->head;
	    if(n != NULL)
	    {
		while(n->next != NULL)
		{
		    n = n->next;
		}
		n->next = p;
	    }
	    else
	    {
		pList->head = p;
	    }
	    success = TRUE;
	}
    }
    return success;
}

void list_free(LIST* pList)
{
    NODE* n = NULL;
    NODE* p = NULL;
    if(pList != NULL)
    {
	n = pList->head;
	while(n != NULL)
	{
	    p = n;
	    n = n->next;
	    free(p);
	}
	pList->head = NULL;
    }
}

void print_list(const LIST* pList)
{
    NODE* p = NULL;
    if(pList != NULL)
    {
	p = pList->head;
	while(p != NULL)
	{
	    printf("%.2f\n", p->f);
	    p = p->next;
	}
    }
}
 
int main()
{
    LIST l;
    char value[16] = {0};
    float f;
    l.head = NULL;
    do
    {
	f = 0;
	printf("Enter a floating point value or Q/q to Quit: ");
	fgets(value, sizeof(value), stdin);
	value[strlen(value)-1] = '\0';
	if(value[0] == 'q' || value[0] == 'Q')
	{
	    break;
	}
	f = (float)atof(value);
	if(list_add_node(&l, f) != TRUE)
	{
	    printf("Error adding node to list\n");
	    break;
	}
    } while(TRUE);	
    if(l.head != NULL)
    {
	print_list(&l);
	list_free(&l);
    }
    return 0;
}



Output:

Code:
$ ./dynarray Enter a floating point value or Q/q to Quit: 110000.00 Enter a floating point value or Q/q to Quit: 111000.00 Enter a floating point value or Q/q to Quit: 111100.00 Enter a floating point value or Q/q to Quit: 111110.00 Enter a floating point value or Q/q to Quit: 111111.00 Enter a floating point value or Q/q to Quit: 111111.10 Enter a floating point value or Q/q to Quit: 111111.11 Enter a floating point value or Q/q to Quit: q 110000.00 111000.00 111100.00 111110.00 111111.00 111111.10 111111.11

...is how to make a basic linked list using dynamic memory allocations for your nodes.

Something like this:

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#ifndef __cplusplus
typedef char bool;
#endif

#ifndef TRUE
#define TRUE     (1)
#define FALSE    (0)
#endif

typedef float* FLOAT_ARRAY;

void print_array(const FLOAT_ARRAY pfa, const size_t count)
{
    size_t i;
    if(pfa != NULL && count > 0)
    {
        for(i = 0; i < count; i++)
        {
            printf("pfa[%d] = %.2f\n", (int)i, pfa[i]);
        }
    }
}

int main()
{
    char value[16] = {0};
    float* p       = NULL;
    size_t l       = 0;
    float f        = 0.0F;

    do
    {
        f = 0.0F;
        printf("Enter a floating point value or Q/q to Quit: ");
        fgets(value, sizeof(value), stdin);
        value[strlen(value)-1] = '\0';
        if(value[0] == 'q' || value[0] == 'Q')
        {
            break;
        }
        f = (float)atof(value);
        if(errno != EINVAL && errno != ERANGE)
        {
            p = (float*)realloc(p, (sizeof(float) * (l + 1)));
            if(p != NULL)
            {
                p[l++] = f;
            }
        }
        else
        {
            printf("Invalid entry: %s\nPlease try again...\n", value);
        }
    } while(TRUE);

    if(l > 0)
    {
        print_array(p, l);
    }
    if(p != NULL)
    {
        free(p);
    }
    return 0;
}


Output:

Code:
$ ./dynarry Enter a floating point value or Q/q to Quit: 1000.00 Enter a floating point value or Q/q to Quit: 1000.01 Enter a floating point value or Q/q to Quit: 1000.10 Enter a floating point value or Q/q to Quit: 1000.11 Enter a floating point value or Q/q to Quit: 1001.00 Enter a floating point value or Q/q to Quit: 1001.01 Enter a floating point value or Q/q to Quit: 1001.10 Enter a floating point value or Q/q to Quit: 1001.11 Enter a floating point value or Q/q to Quit: 1010.00 Enter a floating point value or Q/q to Quit: 1010.01 Enter a floating point value or Q/q to Quit: 1010.10 Enter a floating point value or Q/q to Quit: 1010.11 Enter a floating point value or Q/q to Quit: 1011.00 Enter a floating point value or Q/q to Quit: q pfa[0] = 1000.00 pfa[1] = 1000.01 pfa[2] = 1000.10 pfa[3] = 1000.11 pfa[4] = 1001.00 pfa[5] = 1001.01 pfa[6] = 1001.10 pfa[7] = 1001.11 pfa[8] = 1010.00 pfa[9] = 1010.01 pfa[10] = 1010.10 pfa[11] = 1010.11 pfa[12] = 1011.00

...if you want to create an "array" where the dimension is allocated dynamically.


MxB
  #4  
Old 10-Feb-2009, 15:10
mas287 mas287 is offline
New Member
 
Join Date: Jun 2008
Posts: 9
mas287 is on a distinguished road

Re: Dynamic 2 dimensional array problem


Thanks for your reply. Yes, I don't want to store 100 arrays as my input data is generated by a random graph. What I need is to have 2 dynamic dimentional array pointer with NODE type.

I believe, I should allocate memory using malloc function.

Example:

CPP / C++ / C Code:

NODE *(**check);

function_memory_allocation()
{
   check = malloc (n * sizeof(NODE));
   for( i = 0; i < n; i++)
    {
       check[i] = malloc(n * sizeof(NODE));
    }
}


The problem is, when n = 500, I manage to get my result, but when n >=500, a problem with segmentation errors occur here. Diff machine give me diff result as the input graph is generated by a random number.

I don't want to have a static 2 dimensional array. I want to make it dynamic, but I have a problem with that.

Please help.
  #5  
Old 10-Feb-2009, 15:30
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 758
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Dynamic 2 dimensional array problem


There are a couple of different ways to allocate 2D arrays.

1) Allocate an array of pointers to an array. So, if you wanted an array of integers of x rows and y columns, you would allocate it like:
CPP / C++ / C Code:
int **array;

// allocate an array of pointers
array = (int**)malloc(x*sizeof(int*));

// now, set each array element to a new array
for(int i=0;i<x;++i) array[i] = (int*)malloc(y*sizeof(int));

// now, if you want to access the integer at row = 3 and column = 5
int j = array[3][5];

2) Another way is to allocate it as just one large array. This saves space as we don't have to allocate space for the address of each array. It is done like so:
CPP / C++ / C Code:
int *array;

// allocate an array of pointers
array = (int*)malloc(x*y*sizeof(int));

// now, if you want to access the integer at row = 3 and column = 5
int j = array[3*y+5];
  #6  
Old 10-Feb-2009, 18:51
mas287 mas287 is offline
New Member
 
Join Date: Jun 2008
Posts: 9
mas287 is on a distinguished road

Re: Dynamic 2 dimensional array problem


Thank you Fakepoo.

I like the first declaration, but it only works if variable array is a dimensional array. I am hoping that array is a pointer as well.

CPP / C++ / C Code:
struct node 
{
   int bil;
   double value;
};

struct node *(**array);

struct node *j;

j = array[3][5];


j is a pointer to a linked list and I want to perform delete operation at certain location (eg: array[3][5]). Therefore I need to declare j as a pointer. Or, do you have any other idea/suggestion?

Is memory allocation for a two dimentional pointer type diff compare to a normal dimensional array?

I have to do this as I don't want to have loop when performing delete operation. I just want to go straight away to the exact place to perform deletion.

Many thanks for your kind help.
  #7  
Old 11-Feb-2009, 08:37
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 758
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Dynamic 2 dimensional array problem


OK. So let me see if I understand what you are trying to do. You have a 2-D array. Each element of the array is a linked list? So, if you have a 10 x 10 array then you have 100 linked lists? If this is the case and you want each element of the array to be a node*, then:
CPP / C++ / C Code:
int x = 10;
int y = 10;
int i,j;

// Create an array that holds each of the subarrays
node ***array = (node***)malloc(x*sizeof(node**));

// Create each subarray
for(i=0;i<x;++i) array[i] = (node**)malloc(y*sizeof(node*));

// Now, you have a 2D array that can hold pointers to node.

// Suppose we need to initialize all of them to NULL
for(i=0;i<x;++i)
{
  for(j=0;j<y;++j)
  {
    array[i][j] = NULL;
  }
}

// Suppose we want to put a linked list at location 3,5
array[3][5] = (node*)malloc(sizeof(node));
array[3][5]->value = 12.25;

// Now, when you are done using array[][], we need to free it
    // Free any linked lists that we allocated
for(i=0;i<x;++i)
{
  for(j=0;j<y;++j)
  {
    if(array[i][j] != NULL)
    {
       // call the function for deleting a linked list here
    }
  }
}
    
    // Free the subarrays
for(i=0;i<x;++i) free(array[i]);
    // Free the array that holds the arrays
free(array);


Now, as far as your definition of node....shouldn't it reference another node? Something like:
CPP / C++ / C Code:
struct node
{
  int bil; // don't know what this is
  double value;
  struct node *next; // this points to the next node in the list
};
  #8  
Old 11-Feb-2009, 15:38
mas287 mas287 is offline
New Member
 
Join Date: Jun 2008
Posts: 9
mas287 is on a distinguished road

Re: Dynamic 2 dimensional array problem


Thank you so much.

You have given me a very clear picture.

I believe that I can do it.

Many thanks.
  #9  
Old 11-Feb-2009, 18:06
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 335
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Dynamic 2 dimensional array problem


Quote:
Originally Posted by fakepoo
CPP / C++ / C Code:
// Suppose we need to initialize all of them to NULL
for(i=0;i<x;++i)
{
  for(j=0;j<y;++j)
  {
    array[i][j] = NULL;
  }
}


Instead of using malloc and then looping to null initialize, simply use calloc instead. You'll save cycles and code/typing.


MxB
 
 

Recent GIDBlogProblems with the Navy (Enlisted) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Convert row elements from two dimensional array to one dimensional arrays ahmetemir MS Visual C++ / MFC Forum 0 01-Feb-2009 05:08
where is the problem and can you fix it (php) oggie MySQL / PHP Forum 8 14-Apr-2008 16:08
My newbie two dimensional array problem Zach C++ Forum 2 04-May-2006 23:21
Need help deleting the last element in the array headphone69 C++ Forum 2 15-Mar-2006 20:31
problem reading to a dynamic array noamfrie C Programming Language 9 02-Jan-2005 19:35

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 13:29.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.