Dynamic Allocation 2D array - c

I need to implement 10 cols by a dynamic row lenght array which can hold a string. So far, i am trying to experiment by using an intiger instead of srings, for simplicity.
this is my code so far:
int** pArray = (int**)malloc(10*sizeof(int*));
for (i = 0; i < 10; i++ )
{
pArray[i] = (int*)malloc(sizeof(int));
}
so now i know i created a 10x1 array. now i need to dynamically realoc each row according to the need that arises..
at this point i am stuck. Any assistance would be much apprieciated

A better approach than reallocating would be be to allocate the rows after you know how much memory is needed.
char ** pArray = (char **)malloc(10*sizeof(char*));
for(i=0;i<10;i++)
{
pArray[i] = NULL;
}
And when you need to allocate row 'i' of size 'n', do
pArray[i] = (char*)malloc(n*sizeof(char));

I think you want the realloc function.

Related

Copying a 2D array to a dynamically allocated 2D array outside of the function

I have fullNames, which is a 2D array that has sorted full names in it and I want to copy its content into sortedNames, which is a 2D array that exists out side of this function. (I get ***sortedNames as a parameter).
I dynamically allocated this array, but the copying does not succeed. The program crashes after the 4th attempt to copy a name from fullNames to sortedNames. Why?
stringcpy and stringlen are functions that I created. They do the same thing as strcpy and strlen does.
/*allocating memory for sortedNames*/
*sortedNames = (char**) malloc(n);/*n is the number of names*/
/*allocating memory for each sortedNames array*/
for (i = 0; i < n; i++)
{
(*sortedNames)[i] = (char*) malloc(stringlen(fullNames[i])+1);
}
/*Copying fullNames into sortedNames*/
for (i = 0; i < n; i++)
{
stringcpy((*sortedNames)[i],fullNames[i]);
}
You do not allocate enough memory for the array of pointers, you should allocate this way:
*sortedNames = (char**)malloc(n * sizeof(char *));
Furthermore, why not use strlen and strcpy in place of stringlen and stringcpy? It this just a typo or do these function perform some extra function?
Regarding the cast on malloc return value, you could remove it if you do not intend to compile your code as C++ and write this:
*sortedNames = malloc(n * sizeof(**sortedNames));
Regarding the extra parentheses around **sortedNames, be aware that they are not necessary so you can remove them or not depending on your local style conventions.
There should be 2 edits as the memory allocated may not be sufficient. This code :
(*sortedNames)[i] = (char*) malloc(n);
allocates memory for n bytes whiles you need memory for (n*the size of string) bytes.The second malloc may work as char occupies 1 byte. But try to use sizeof() to make it system independent.
The correct code would be :
(*sortedNames)[i] = malloc(n*sizeof(char *));

Memory leak in C

I am using GTK, and I am not sure with malloc() function here. Valgrind gives me a memory leak, what I am doing bad?
at first I create pointer to pointer to pointer to GTK widget, because I need three dimensional array.
GtkWidget*** widgets;
and I am using malloc like this:
widgets = malloc((1)*sizeof(GtkWidget**));
for(i = 0; i<= l-1; i++) // l = 4 in my case
{
widgets[i] = malloc((1)*sizeof(GtkWidget*));
for(j = 0; j<=3; j++) // 4 is number of elements in this dimension
{
widgets[i][j] = malloc((1)*sizeof(GtkWidget));
}
}
and at the end I am doing this:
widgets[0][0] = gtk_menu_item_new_with_label("MyLabel");
gtk_menu_shell_append(GTK_MENU_SHELL(indicator_menu), widgets[0][0]);
my array can be smaller and bigger, so I am using dynamic allocation of array, my maximal array indexes are something like widgets[3][3].
I did not post whole code, because it is pretty long, I sent here just the parts for which was valgrind complaining to. What I am doing bad? thank you.
You're only allocating the size of a pointer, when you mean to allocate an array of pointers.
// this will allocate a single character pointer
char ** ptr = malloc(1 * sizeof(char *));
// this will allocate n character pointers
char ** ptr = malloc(n * sizeof(char *));
So if you want a two dimensional array of dimension NxM, you'll need to allocate an array of size N, then walk through that array from 0 to N-1 and allocate arrays of size M.
What you're doing now is assigning pointers returned from malloc to memory you don't own. Is what you actually want a two-dimensional array of pointers to GtkWidget structures?
Using l as a local variable is not a good idea. It is very easy to make a mistake between l and 1, in some editors they look very much the same.
widgets = malloc((l)*sizeof(GtkWidget**)); //is what you needed
iso
widgets = malloc((1)*sizeof(GtkWidget**));
Over here with syntax highlighting the problem immediately appears.
So another suggestion is to for sure use an editor with syntax highlighting

Accessing elements in a two dimensional lattice C

Why can I not access Lattice using [ ][ ] without raising a seg fault?
int *LatticeHeight;
int **Lattice;
LatticeHeight = (int*)malloc(Height*sizeof(int));
Lattice = (int**)malloc(Length*sizeof(LatticeHeight));
for(i=0;i<Height; i++)
{
for(j=0; j<Length; j++)
{
Lattice[j][i] = 0;
}
}
I'm interpreting this as;
I have my pointer to one dimensional array of height
Then I set Lattice so that is can store Length-many copies of LatticeHeight (making a grid)
Then I access each element of the lattice and set it's value to 0
Moreover could someone explain why this works in 1D but not in 2D, i.e.
for(i=0;i<Height;i++)
{
LatticeHeight[i] = 0;
}
Does not throw a seg fault
You didn't allocate the array properly. Your first malloc allocates one row; your second malloc allocates space to store a pointer to each row but it does not actually allocate any rows to go in there (and it does not have any association to the single row you allocated earlier, either).
The simplest way to write this code, if you do not require to have rows of different lengths to each other, is to allocate a single memory block:
int (*Lattice)[Length] = calloc( Height, sizeof *Lattice );
If you do want to have a jagged array for some reason (i.e. each row is allocated in a separate memory block) then the code is:
int **Lattice = malloc( Height * sizeof *Lattice );
for ( size_t row = 0; row != Height; ++row )
Lattice[row] = calloc( Length * sizeof **Lattice );
Note that calloc allocates the memory and also zeroes it, so you don't need your zero loop afterwards, and don't cast malloc
I think you should initialize your array like this:
Lattice = (int**)malloc(Length*sizeof(int*));
for(int i = 0; i < Length; ++i) {
LatticeHeight = (int*)malloc(Height*sizeof(int));
}
You have to allocate memory for Lattice which is a pointer to a pointer to int.
Lattice = malloc(Length * sizeof(LatticeHeight));
And then iterate through the "array" of pointers to int that you just have created and allocate memory for each one, like this.
for(i = 0; i < Lenght; i++)
LatticeHeight = malloc(Height * sizeof(int));
With that you would have a two-dimensional "array".
Although, as Matt McNabb said, there are other options for what you want to do.

Declaring and Initializing 2D array of unknown size in C

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
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
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);

How to create at runtime a two dimensional array in C

I cannot create a 2D array from 2 variables (eg int arr[i][j] not allowed) so how would I create a dynamically sized 2D array?
The dimensions of the array are only known at runtime in my program. The array is to represent a grid. How would I code this in C?
First allocate an array of pointers.
/* size_x is the width of the array */
int **array = (int**)calloc(size_x, sizeof(int*));
Then allocate each column.
for(int i = 0; i < size_x; i++)
{
/* size_y is the height */
array[i] = (int*)calloc(size_y, sizeof(int));
}
You can access the elements with array[i][j]. Freeing the memory is done in 'reverse' order:
for(int i = 0; i < size_x; i++)
{
free(array[i]);
}
free(array);
You have to allocate a 1-dimensional array:
int* array = calloc(m*n, sizof(int));
And access it like this:
array[i*n + j]
The compiler does exactly this when accessing two-dimensional arrays, and will probably output the same code when n can be guessed at compile time.
This is a FAQ on comp.lang.c (I took the liberty to add the c-faq tag), it even has a FGA (frequently given answer :-)
See http://c-faq.com/aryptr/index.html, 6.16 How can I dynamically allocate a multidimensional array?
In C a multidimensional array is just an array for which each element is another array.
So you need to first allocate memory for one array (the rows). You can use the malloc() function which will return a pointer to the array.
Then you iterate through the array and for each element you allocate memory for the number of columns.
NOTE: don't forget to free the memory you manually allocate with the free() function in the same way you used malloc() to allocate it.
Some of the examples show multiple (more than 2) allocations for the array; it is perfectly feasible to do it in just two allocations (error checking omitted) for an n × m array:
int **array = calloc(m, sizeof(*array));
int *data = calloc(m * n, sizof(*data));
for (int i = 0; i < m; i++)
array[i] = &data[i * n];
...use array[i][j]...
free(array[0]);
free(array);

Resources