reallocation of 2d arrays in c - c

I want to reallocate a 2d array, so that the arrays in the second array become bigger, so the things I want to store are bigger than the arrays I want to store them in and I want to make the arrays bigger. The problem is that I do not really know how to do this. I got it to compile without errors, but in Valgrind I saw a lot of memory errors, so I do something wrong. I saw a previous question about this here but I do not really understand it, so any help and explanation on how to do this would be greatly appreciated.
I have this so far.
int **create2darray(int a, int b) {
int i;
int **array;
array = malloc(a * sizeof(int *));
assert(array != NULL);
for (i = 0; i < a; i++) {
array[i] = calloc(b, sizeof(int));
assert(array[i] != NULL);
}
return array;
}
int **reallocArray(int **array, int size, int i) {
int i;
int **safe_array;
safe_array = realloc(*array ,2 * size);
assert(safe_array != NULL);
array = safe_array;
return array;
}
void free2DArray(int **array, int m) {
int i;
for (i = 0; i < m; i++) {
free(array[i]);
}
}
int main(int argv, char *argc[]) {
int i;
int size;
int **testArray = create2darray(1, 10);
size = 10;
for(i = 0; i < size; i++) {
testArray[0][i] = 2;
}
testArray[0] = reallocArray(testArray, size, 0);
size = 2 * size;
for(i = 9; i < size; i++) {
testArray[0][i] = 3;
}
for(i = 0; i < size; i++) {
printf("%d", testArray[0][i]);
free2DArray(testArray, size);
}
return 0;
}

You need a function reallocArray which realaoctes the outer array and all the inner arrays too.
Adapt youre code like this:
#include <malloc.h>
int **reallocArray( int **array, int oldSizeA, int newSizeA, int newSizeB )
{
// realloc the array of pointers ( allocates new memory if array == NULL )
int **safe_array = realloc( array, newSizeA * sizeof( int* ) );
assert(safe_array != NULL);
if ( safe_array == NULL )
return array;
array = safe_array;
// realloc the inner arrays of int ( allocates new memory if i >= oldSizeA )
for ( int i = 0; i < newSizeA; i ++ )
{
int *temp = NULL; // allocate new memory if i >= oldSizeA
if ( i < oldSizeA )
temp = array[i]; // reallocate array[i] if i < oldSizeA
temp = realloc( temp, newSizeB * sizeof( int ) );
assert( temp != NULL );
if ( temp == NULL )
return array;
array[i] = temp;
}
return array;
}
Use function reallocArray in your function create2darray to create your array. If the input paramter of ralloc is NULL, then new dynamic memory is allocated.
int **create2darray( int sizeA, int sizeB )
{
return reallocArray( NULL, 0, sizeA, sizeB );
}
First you have to free the inner arrays of int in a loop, then you have to free the array of pointers:
void free2DArray( int **array, int sizeA )
{
for (int i = 0; i < sizeA; i ++)
free( array[i] );
free( array );
}
int main( int argv, char *argc[] ){
int sizeA = 1;
int sizeB = 10;
int **testArray = create2darray( sizeA, sizeB );
for ( int i = 0; i < sizeB; i++ ) {
testArray[0][i] = 2;
}
int oldSizeA = sizeA;
int oldSizeB = sizeB;
sizeB = 2*sizeB;
testArray = reallocArray( testArray, oldSizeA, sizeA, sizeB );
for( int i = oldSizeB; i < sizeB; i++ ) {
testArray[0][i] = 3;
}
for( int i = 0; i < sizeB; i++ ) {
printf("%d", testArray[0][i]);
}
free2DArray(testArray, sizeA );
return 0;
}

In Free2DArray(), you free() the individual arrays of integers, but not the "outer" dimension of the array which holds the integer pointers.
You could add another call to free() after the loop to take care of that.
In main():
for(i = 0; i <size; i++) {
printf("%d", testArray[0][i]);
free2DArray(testArray, size);
}
you will end up free()-ing the (inner) integer arrays multiple times.
The call to free2DArray() should be outside the loop.

Related

Two sum leetcode clang

I practice in c language, here is the exercise:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example :
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Here my attempt:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
static int r[2];
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if(i!=j&&(nums[i]+nums[j])==target){
r[0]=i;
r[1]=j;
}
}
}
return r;
}
But Irecieve a wrong answer:
enter image description here
The function definition does not satisfies the requirement specified in the comment
Note: The returned array must be malloced, assume caller calls free()
Moreover the parameter
int* returnSize
is not used within your function definition.
It seems the function should be defined the following way as it is shown in the demonstration program below. I assume that any element in the source array can be present in the result array only one time.
#include <stdio.h>
#include <stdlib.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *twoSum( int *nums, int numsSize, int target, int *returnSize )
{
int *result = NULL;
*returnSize = 0;
for (int i = 0; i < numsSize; i++)
{
for (int j = i + 1; j < numsSize; j++)
{
if (nums[i] + nums[j] == target)
{
int unique = result == NULL;
if (!unique)
{
unique = 1;
for (int k = 1; unique && k < *returnSize; k += 2)
{
unique = nums[k] != nums[j];
}
}
if (unique)
{
int *tmp = realloc( result, ( *returnSize + 2 ) * sizeof( int ) );
if (tmp != NULL)
{
result = tmp;
result[*returnSize] = i;
result[*returnSize + 1] = j;
*returnSize += 2;
}
}
}
}
}
return result;
}
int main( void )
{
int a[] = { 2, 7, 11, 15 };
int target = 9;
int resultSize;
int *result = twoSum( a, sizeof( a ) / sizeof( *a ), target, &resultSize );
if (result)
{
for (int i = 0; i < resultSize; i += 2 )
{
printf( "%d, %d ", result[i], result[i + 1] );
}
putchar( '\n' );
}
free( result );
}
The program output is
0, 1
Though as for me then I would declare the function like
int *twoSum( const int *nums, size_t numsSize, int target, size_t *returnSize );
The brute force approach is very simple to this problem.
int* twoSum(int* arr, int n, int t, int* returnSize){
int *res=malloc(2*sizeof(int));
*returnSize=2;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if((arr[i]+arr[j])==t)
{
res[0]=i;
res[1]=j;
goto exit;
}
}
}
exit:
return res;
}

Why am I getting errors when debugging realloc?

int *dynArr(int* arr, int n, int isEven) {
int count = 0;
int* t = (int*)calloc(n, sizeof(int));
assert(t);
if (isEven == 1) {
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
t[count++] = arr[i];
}
}
}
t = (int*)realloc(*t, count * sizeof(int));
return t;
}
void main() {
int a[] = { 1,8,3,6,11 };
int n = sizeof(a) / sizeof(int);
int isEven = 1;
int* arr = dynArr(a, n, isEven);
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
}
}
The problem is when I'm returning the array I don't get any output, When I'm debugging I get this error: "Unhandled exception at 0x7A08B54D (ucrtbased.dll) in homelab8.exe: 0xC0000005: Access violation reading location 0x00000004."
Someone have an idea how do I fix this?
First of all, you are passing a bad parameter to realloc. This would easily have been caught had you been using your compiler's warnings.
The other major issue is that you are accessing n elements of the array pointed by arr, but it doesn't have n elements.
Since you have two values to return, you will need to return through arguments (or return a struct).
// Returns 0 on success.
// Returns -1 and sets errno on error.
int filter_even_or_odd(
int **filtered_arr_ptr, // The address of a variable that accepts output.
size_t *filtered_n_ptr, // The address of a variable that accepts output.
int *arr,
size_t n,
int keep_even // Keep even or keep odd?
) {
size_t filtered_n = 0;
int *filtered_arr = malloc( sizeof(int) * n );
if (!filtered_arr)
return -1;
int to_keep = keep_even ? 0 : 1;
for ( size_t i = 0; i < n; i++ ) {
if ( arr[i] % 2 == to_keep ) {
filtered_arr[ filtered_n++ ] = arr[i];
}
}
int *tmp = realloc( filtered_arr, sizeof(int) * filtered_n );
if (tmp)
filtered_arr = tmp;
*filtered_arr_ptr = filtered_arr;
*filtered_n_ptr = filtered_n;
return 0;
}

Why this counting sort return input instead of sorted table?

I'm writing counting sort in C. N is the number of elements in table which is to be sorted, k is max value that any of this element can be. However, this code, leaves me with the same table as the input. What's wrong?
void countingSort(int *tab, int n, int k) {
int *counters = (int *)malloc(k * sizeof(int));
int *result = (int *)malloc(n * sizeof(int*));
for (int i = 0; i < k; i++) {
counters[i] = 0;
}
for (int i = 0; i < n; i++) {
counters[tab[i]]++;
}
int j = 0;
for (int i = 0; i < k; i++) {
int tmp = counters[i];
while (tmp--) {
result[j] = i;
j++;
}
}
tab = result;
}
There are some problems in your code:
int *result = (int *)malloc(n * sizeof(int*)); uses an incorrect size. The array element type is int, not int*. You should write:
int *result = (int *)malloc(n * sizeof(int));
or better:
int *result = (int *)malloc(n * sizeof(*result));
note also that the cast is useless in C, unlike C++ where it is mandatory:
int *result = malloc(n * sizeof(*result));
you could avoid the extra initializing loop by using calloc():
int *counters = calloc(n, sizeof(*counters));
a major problem: the result array is never returned to the caller: tab = result; just modifies the argument value, not the caller's variable. You should instead use the tab array to store the results directly.
you do not free the arrays, causing memory leaks.
you do not test for allocation success, causing undefined behavior if memory is not available. You should return an error status indicating this potential problem.
Here is a corrected version:
// assuming all entries in tab are > 0 and < k
int countingSort(int *tab, int n, int k) {
int *counters = calloc(k, sizeof(*counters));
if (counters == NULL)
return -1;
for (int i = 0; i < n; i++) {
counters[tab[i]]++;
}
int j = 0;
for (int i = 0; i < k; i++) {
int tmp = counters[i];
while (tmp--) {
tab[j++] = i;
}
}
free(counters);
return 0;
}
You pass tab to the function by pointer. However you need to change not the value, but address of the variable. So you should pass address of the pointer to countingSort.
void countingSort(int **tab, int n, int k)

Return two pointers from a function in c

I know that you can return a pointer to the first element of an array in c by doing:
#include <stdlib.h>
#include <stdio.h>
int *my_func(void);
int main(void)
{
int *a;
int i;
a = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
}
free(a);
return 0;
}
int *my_func(void)
{
int *array;
int i;
array = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
}
return array;
}
But if I wanted to return two pointers instead of just one, I tried:
#include <stdlib.h>
#include <stdio.h>
int *my_func(int *);
int main(void)
{
int *a;
int *b;
int i;
a = my_func(b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
printf("b[%d] = %d\n", i, b[i]);
}
free(a);
free(b);
return 0;
}
int *my_func(int *array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
array2 = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
array2[i] = i;
}
return array;
}
But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!
I can think of three (and a half) simple ways to return multiple items of any kind from a C-function. The ways are described below. It looks like a lot of text, but this answer is mostly code, so read on:
Pass in an output argument as you have done, but do it correctly. You have to allocate space for an int * in main() and then pass the pointer to that to my_func.
In main():
a = my_func(&b);
my_func() becomes:
int *my_func(int **array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
*array2 = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
(*array2)[i] = i;
}
return array;
}
Make your function allocate array of two pointers to the int arrays you are trying to allocate. This will require an additional allocation of two int pointers, but may be worth the trouble.
main() then becomes:
int main(void)
{
int **ab;
int i;
ab = my_func(b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab[0][i]);
printf("b[%d] = %d\n", i, ab[1][i]);
}
free(ab[0]);
free(ab[1]);
free(ab);
return 0;
}
my_func() then becomes:
int **my_func(void)
{
int **arrays;
int i, j;
arrays = calloc(2, sizeof(int *));
arrays[0] = calloc(3, sizeof(int));
arrays[1] = calloc(3, sizeof(int));
for(j = 0; j < 2; j++)
{
for(i = 0; i < 3; i++)
{
arrays[j][i] = i;
}
}
return arrays;
}
Return a structure or structure pointer. You will need to define the structure, and decide whether you want to return the structure itself, a newly allocated pointer to it, or pass it in as a pointer and have my_func() fill it in for you.
The structure definition would look something like this:
struct x
{
int *a;
int *b;
}
You would then rephrase your current functions as one of the following three options:
Direct passing of structure (not recommended for general use):
int main(void)
{
struct x ab;
int i;
ab = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab.a[i]);
printf("b[%d] = %d\n", i, ab.b[i]);
}
free(ab.a);
free(ab.b);
return 0;
}
struct x my_func(void)
{
struct x ab;
int i;
ab.a = calloc(3, sizeof(int));
ab.b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab.a[i] = i;
ab.b[i] = i;
}
return ab;
}
Return a pointer to a dynamically allocated structure (this is a pretty good option in general):
int main(void)
{
struct x *ab;
int i;
ab = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab->a[i]);
printf("b[%d] = %d\n", i, ab->b[i]);
}
free(ab->a);
free(ab->b);
free(ab);
return 0;
}
struct x *my_func(void)
{
struct x *ab;
int i;
ab = malloc(sizeof(struct x));
ab->a = calloc(3, sizeof(int));
ab->b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab->a[i] = i;
ab->b[i] = i;
}
return ab;
}
Allocate the structure in main() and fill it in in my_func via a passed-in pointer. This option is often used in a way where my_func would allocate the structure if you pass in a NULL pointer, otherwise it would return whatever you passed in. The version of my_func shown here has no return value for simplicity:
int main(void)
{
struct x ab;
int i;
my_func(&ab);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab.a[i]);
printf("b[%d] = %d\n", i, ab.b[i]);
}
free(ab.a);
free(ab.b);
return 0;
}
void my_func(struct x *ab)
{
int i;
ab->a = calloc(3, sizeof(int));
ab->b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab->a[i] = i;
ab->b[i] = i;
}
return;
}
For all the examples shown here, don't forget to update the declaration of my_func at the top of the file, although I am sure any reasonable compiler will remind you if you forget.
Keep in mind also that these are just three options I pulled out of my brain at a moments notice. While they are likely to cover 99% of any use cases you may come up against any time soon, there are (probably lots of) other options out there.
Function parameters are its local variables. Functions deal with copies of values of the supplied arguments.
You can imagine your function definition and its call the following way
a = my_func(b);
int *my_func( /* int *array2 */ )
{
int *array2 = b;
//...
}
So any changes of the local variable array2 inside the function do not influence on the original argument b.
For such a function definition you have to pass the argument by reference that is the function should be declared like
int *my_func( int **array2 );
^^
There are many ways to implement the function. You could define a structure of two pointers as for example
struct Pair
{
int *a;
int *b;
};
and use it as the return type of the function
struct Pair my_func( void );
Another approach is to pass to the function an array of pointers to the original pointers.
The function can look as it is shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
size_t multiple_alloc( int ** a[], size_t n, size_t m )
{
for ( size_t i = 0; i < n; i++ ) *a[i] = NULL;
size_t k = 0;
for ( ; k < n && ( *a[k] = malloc( m * sizeof( int ) ) ) != NULL; k++ )
{
for ( size_t i = 0; i < m; i++ ) ( *a[k] )[i] = i;
}
return k;
}
#define N 2
#define M 3
int main(void)
{
int *a;
int *b;
multiple_alloc( ( int ** [] ) { &a, &b }, N, M );
if ( a )
{
for ( size_t i = 0; i < M; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
}
if ( b )
{
for ( size_t i = 0; i < M; i++ ) printf( "%d ", b[i] );
putchar( '\n' );
}
free( a );
free( b );
return 0;
}
The program output is
0 1 2
0 1 2
#include <stdlib.h>
#include <stdio.h>
int *my_func(int **);
int main(void)
{
int *a;
int *b;
int i;
b=(int *)malloc(sizeof(int));
a = my_func(&b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
printf("b[%d] = %d\n", i, b[i]);
}
free(a);
free(b);
return 0;
}
int *my_func(int **array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
*array2 =calloc(3,sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
*((*array2)+i)=i;//or (*array2)[i]
}
return array;
}
Pass the pointer by reference. Because its the same logic as, to manipulate an integer block you need to pass a pointer to it. Similarly, to manipulate a pointer, you will have to pass a pointer to it(i.e. pointer to pointer).

How can I create a function for dynamic allocation for 2d array in c? [duplicate]

This question already has answers here:
Allocate memory 2d array in function C
(8 answers)
C. Segmentation Fault when function modifies dynamically allocated 2d array
(3 answers)
Closed 8 years ago.
#include<stdio.h>
#include<stdlib.h>
void aloc_dinamic(double **M)
{
int i;
M = (double **)malloc(m*sizeof(double *));
for(i=0;i<m;i++)
M[i] = (double *)calloc(m, sizeof(double));
}
int main(void)
{
double **H;
aloc_dinamic(H)
}
How can I create a function for dynamic allocation for 2d array in c?
I tried this, but it doesn't work.
#include <stdlib.h>
double ** aloc_dynamic( size_t n, size_t m )
{
double **p = ( double ** )malloc( n * sizeof( double * ) );
for ( size_t i = 0; i < n; i++ )
{
p[i] = ( double * )malloc( m * sizeof( double ) );
}
return p;
}
int main(void)
{
size_t n = 5;
size_t m = 10;
double **p = aloc_dynamic( n, m );
// before exiting the function free the allocated memory
}
... and with the corresponding free function
#include<stdio.h>
#include<stdlib.h>
double** alloc_2d(int y_extent, int x_extent)
{
int y, x;
double ** array = (double**)malloc(y_extent * sizeof(double*));
for (y = 0 ; y < y_extent ; ++y) {
array[y] = (double*)malloc(sizeof(double) * x_extent);
for(x = 0 ; x < x_extent ; ++x) {
array[y][x] = 0.0;
}
}
return array;
}
void free_2d(double** array, int y_extent)
{
int y;
for(y = 0 ; y < y_extent ; ++y) {
free(array[y]);
}
free(array);
}
int main(void)
{
double **H = alloc_2d(50,100);
H[10][10] = 0.0; // for example
free_2d(H, 50);
return 0;
}
You can do it like this:
// We return the pointer
int **get(int N, int M) /* Allocate the array */
{
/* Check if allocation succeeded. (check for NULL pointer) */
int i, **table;
table = malloc(N*sizeof(int *));
for(i = 0 ; i < N ; i++)
table[i] = malloc( M*sizeof(int) );
return table;
}
// We don't return the pointer
void getNoReturn(int*** table, int N, int M) {
/* Check if allocation succeeded. (check for NULL pointer) */
int i;
*table = malloc(N*sizeof(int *));
for(i = 0 ; i < N ; i++)
*table[i] = malloc( M*sizeof(int) );
}
void fill(int** p, int N, int M) {
int i, j;
for(i = 0 ; i < N ; i++)
for(j = 0 ; j < M ; j++)
p[i][j] = j;
}
void print(int** p, int N, int M) {
int i, j;
for(i = 0 ; i < N ; i++)
for(j = 0 ; j < M ; j++)
printf("array[%d][%d] = %d\n", i, j, p[i][j]);
}
void free2Darray(int** p, int N) {
int i;
for(i = 0 ; i < N ; i++)
free(p[i]);
free(p);
}
int main(void)
{
int **p;
//getNoReturn(&p, 2, 5);
p = get(2, 5);
fill(p ,2, 5);
print(p, 2, 5);
free2Darray(p ,2);
return 0;
}
Remember a 2D array is a 1D array of pointers, where every pointer, is set to another 1D array of the actual data.
Image:
I suggest you to read the explanation here.

Resources