Dynamic 2 Dimensional Array in C

Status
Not open for further replies.

H-Hour

Ars Scholae Palatinae
606
cacheMem is my 2 dimen array of ints
valdbit is a 1 dimen array of ints

Code:
int main(int argc, char *argv[], int blockSizeInWords, int numberOfSets, int blocksPerSet)
{
	int i;
	int j;

	int *cacheMem = (int *)malloc(numberOfSets * sizeof(int));
        for(i = 0; i < (blocksPerSet * blockSizeInWords); i++) 
	{
		 cacheMem[i] = (int *)malloc(blocksPerSet * blockSizeInWords * sizeof(int));	
		
	}
	
	int *validBit = (int *)malloc(numberOfSets * blocksPerSet * blockSizeInWords * sizeof(int));
	
    char line[MAXLINELENGTH];
    stateType state; /* Defined Globally */
    FILE *filePtr;

this is my code tthes are my errors using .net Academic


Code:
e:\EECS370\Cache Simulator\simulate.c(57): warning C4047: '=' : 'int' differs in levels of indirection from 'int *'
e:\EECS370\Cache Simulator\simulate.c(61): error C2143: syntax error : missing ';' before 'type'
e:\EECS370\Cache Simulator\simulate.c(63): error C2143: syntax error : missing ';' before 'type'
e:\EECS370\Cache Simulator\simulate.c(64): error C2275: 'stateType' : illegal use of this type as an expression
e:\EECS370\Cache Simulator\simulate.c(64): error C2146: syntax error : missing ';' before identifier 'state'
e:\EECS370\Cache Simulator\simulate.c(64): error C2144: syntax error : '<Unknown>' should be preceded by '<Unknown>'

line 57 being the statement inside the for loop

i have no idea what im doing wrong here im new to C but have been programming C++ for a while. i just can't see my error
 
The thing generating the errors is that unlike in C++, declarations have to precede code in C. As such, you'll need to have something like
Code:
int i;
int j;

int *validBit;
char line[MAXLINELENGTH];
stateType state;
FILE *filePtr;
before the for loop.

The matter generating the warning is an error also: if cacheMem is going to hold an int pointer, cacheMem should be declared as int **:
Code:
int **cacheMem = (int **)malloc(numberOfSets * sizeof(int **));
Also that for loop should probably be running through 0 to numberOfSets, not blocksPerSet * blockSizeInWords.

Another issue is that the form of the function main() is very strictly constrained. Portably, it can only be declared as int main() or as int main(int argc,char *argv[]) (or equivalent). On some platforms, it can be declared as int main(int argc,char *argv[],char *envp[]), but this isn't strictly portable. Some platforms (Windows) don't care, some care a lot. At anyrate, there's little chance that anything is going to be able to set the parameters blockSizeInWords, numberOfSets or blocksPerSet usefully. Are these meant to be command-line parameters?

So this gives us something like:
Code:
#include <stdlib.h>
#include <stdio.h>

/* 
  definition of MAXLINELENGTH,
  typedef of stateType
  etc. up here somewhere
*/
[...]

stateType state;

int main(int argc,char **argv)
{
    int i,j;
    int **cacheMem=0;
    int *validBit=0;
    char line[MAXLINELENGTH];
    FILE *filePtr; 

    /*
       parse command line arguments, etc.
       set blockSizeInWords, numberOfSets, blocksPerSet
    */
    [...]

    cacheMem=(int **)malloc(numberOfSets*sizeof(int *));
    for (i=0;i<numberOfSets;++i)
    {
        cacheMem[i]=(int *)malloc(blocksPerSet*blockSizeInWords*sizeof(int));
    }

    validBit=(int *)malloc(numberOfSets*blocksPerSet*blockSizeInWords*sizeof(int));

    /* rest of code ... */
    [...]
}

You don't need to initialise those pointers to zero - I just think it's a good habit, which makes catching bugs later easier.

Alternatives to this sort of scheme for making 2-dimensional dynamic arrays in C are:

  • Use a one-dimensional array and index it like:
    Code:
    int *the_array=(int *)malloc(row_length*column_length*sizeof(int));
    /* the_array[i][j]=3 */
    the_array[i*column_length+j]=3;
  • Allocate a single block of memory for the data, with some extra room at the front to hold the pointers into it. As it involves only one allocation, it's generally quicker to set up and more memory efficient. It's also easier to tidy up afterwards, as there's only one free() required.
    Code:
    int **the_array;
    int i,offset;
    
    the_array=(int **)malloc(row_length*sizeof(int *) + row_length*column_length*sizeof(int));
    offset=row_length*sizeof(int *);
    for (i=0;i<row_length;++i,offset+=column_length*sizeof(int))
        the_array[i]=(int *)(offset+(char *)the_array);
    
    [...]
    
    the_array[i][j]=3;
    
    [...]
    
    free(the_array);
    Note that in this fragment, offset refers to the offset in bytes from the start of the allocated block to the region corresponding to a given row. That's why the cast to (char *) is required in the statement in the for loop.
  • If you can use a C compiler that supports the latest C standard, C99, then you get variable length arrays for free, which makes life a lot easier. You can then just say:
    Code:
    int the_array[row_length][column_length];
    [...]
    and the_array will act like an automatic variable. Be cautious though: typically this will be allocated on the stack, and for large arrays you run the risk of hitting implementation limits of your platform. Stack size is often more limited than potential heap size.


Caveat: I haven't actually tried to compile this code - there are sure to be bugs and typos. But hopefully you get the idea! :)
 

limbs

Ars Scholae Palatinae
1,058
cacheMem = (int *)malloc(blocksPerSet * blockSizeInWords * sizeof(int));
Arrggghhhhh! Don't ever, ever, ever, ever cast the return of malloc in C. Ever! It can hide errors and you just don't need to do it! This of course assumes that the .net C compiler actually complies to the standard!

Also, using sizeof(int) is also bad practice. In this case it's not a big problem, but you may want to change your variable type in the future (maybe to long?) To enable you to avoid changing all your relevant mallocs you could use sizeof(*cacheMem) - more portable.

Take out all your malloc casts, make sure your sizeof(xxx)s are correct and recompile.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
You have a number of problems here. First of all, main has exactly 2 legal definitions:

Code:
    int main (void);
    int main (int, char **);

Some implementations allow a third parameter (also of type char **, I believe), but you should stick with the definitions above; any others can lead to undefined behavior.

Second, you're getting your dimensions confused. Your malloc loop should be looping on numberOfSets, since that's your first dimension.

The best way for me to explain is to show it:

Code:
#include <stdlib.h>
#include <stdio.h>

/*
** Procedure:  arr2dalloc
** Purpose:    Dynamically creates a 2d array of int
** Inputs:     d0                 -- size of first dimension
**             d1                 -- size of second dimension
** Outputs:    none
** Returns:    int **             -- pointer to first element of 
**                                   2d array
**                                -- NULL if failure
*/
int **arr2dalloc (int d0, int d1)
{
    int **a = NULL;
    int i;

    /*
    ** Allocate a d0-element array of int *.  We're
    ** using sizeof *a instead of sizeof (int *)
    ** so we don't have to bother remembering what
    ** the base type of a is.  We could change it
    ** to long, double, whatever, and the statement
    ** below will allocate the proper amount of
    ** memory.
    **
    ** if base type is int **a, then
    **     sizeof a   = sizeof (int **)
    **     sizeof *a  = sizeof (int *)
    **     sizeof **a = sizeof (int)
    */
    a = malloc (d0 * sizeof *a);
    if (a)
    {
        /*
        ** If any of the malloc operations below
        ** fail, set fail flag to 1, which will
        ** tell us to free any resources currently
        ** allocated.
        */
        int fail = 0;

        /*
        ** For each element in a, allocate a d1-element
        ** array of int.
        */
        for (i = 0; i < d0; i++)
        {
            a[i] = malloc (d1 * sizeof **a);
            if (!a[i])
            {
                /*
                ** malloc failed.  Set the fail
                ** flag and break out of the loop
                ** immediately.
                */
                fail = 1;
                break;
            }
        }

        if (fail)
        {
            /*
            ** There was a failure in a malloc operation.
            ** Free any memory already allocated.  Start
            ** from the last successfully allocated element
            ** and work backward; this way we don't need
            ** to introduce another variable.
            */

            i--;
            while (i >= 0)
            {
                free (a[i--]);
            }

            free (a);
            a = NULL;
        }
    }

    return a;
}

/*
** main
*/
int main (void)
{
    int **a1 = NULL;
    int i;
    int j;

    a1 = arr2dalloc (5, 10); /* int a1[5][10] */

    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 10; j++)
        {
            a1[i][j] = i*10 + j;
            printf ("a1[%02d][%02d] = %03d\n", i, j, a1[i][j]);
        }
    }

    /*
    ** Properly deallocating the array is left as an exercise
    ** for the reader.  Use the code in arr2dalloc as a guide.
    */
    
    return 0;
}

Hope that makes sense.
 
Status
Not open for further replies.