1

I plan to create an 2D array of a pointer derived from typedef struct

Let's say the typedef struct is named "Items" and contains mixed variables of strings and integers.

I will declare two intvariables namely typenum and typetotal. These two integers will start off from Zero and adds up when the input data matches with certain function.

In the array,Items *type[][], basically type[][] is Items *type[typenum][typetotal] but I cannot do this since I will declare typenum and typetotal as zero at the declaration part.

I tried initializing the array through Items *type[][] = {{0},{0}} but this generates error.

Any advice? Some told me to use malloc() on this, but I simply do not know how.

*Using Tiny C on Windows

1

2 Answers 2

3

Use dynamic memory allocation.

Items **type;
type = malloc(sizeof (Items *) * typenum);

for (int i = 0; i < typenum; i++)
    type[i] = malloc(sizeof Items) * typetotal);

You need to manually free the allocated memory after using the array.

for (int i = 0; i < typenum; i++)
    free(types[i]);

free(types);

Here is a tutorial on it: http://www.eskimo.com/~scs/cclass/int/sx9b.html

Sign up to request clarification or add additional context in comments.

5 Comments

@Rafi Kamal Will this code work if I want to initialize single bracket array?
@BeginnerC You mean 1D array? It will work with some modification. Have a look at this tutorial: cplusplus.com/reference/cstdlib/malloc
@RafiKamal Can't I put the free(types[i]; after type[i] = malloc(sizeof Items) * typetotal);?
malloc is used for allocating memory to a pointer. free is for freeing the allocated memory when your program no longer needs it. You will call free only after you are done with the array. Please check the two tutorials I've given, you'll find detailed information.
0

If typenum and typetotal increase as your program runs be sure to use realloc, which will reallocate more memory and keep the contents. You'll need to allocate the first dimension of the array like this:

myArray = realloc(myArray, sizeof(Items*) * typenum);

and then allocate the second dimension for each of the first:

for(...)
    myArray[i] = realloc(myArray[i], sizeof(Items) * typetotal);

4 Comments

Will I use realloc everytime when the typenum and typetotal increases?
That's right. Beware of running out of memory, in which it'll return NULL but leave the old memory allocated, not freed, likely memory leak!!
Just so that it is clear to me, I shall put type[i] = malloc(sizeof Items) * typetotal) first then below it, I will put your suggested code, type[i] = realloc(type[i],sizeof(Items) * typetotal); Then after that, I will add free(type[i]); then I will end the bracket for the for(...) and put free(types);?
no, use realloc instead. When you pass NULL into the realloc call it'll act the same as malloc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.