1

I'm supposed two data types, which contain a dynamically allocated array, and two variables akt and max, which indicate the position of the last element in the array and the length of the array respectively. Two functions should also be written, so that the first one adds new elements to the array, and reallocate the array in a doubled space if there's no enough space. the second function inserts also new elements into the array but it reallocates the array, such that its size is bigger by only one place.so my code goes like that:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>

struct DynArray
{
    int *p, max, akt = 0;
};
struct DynArrayMin
{
    int *p, max, akt = 0;
};
void dyn_arr_add(struct DynArray* d, int x)
{
    if ((d->akt)>(d->max) - 1)
    {
        d->p = (int*)realloc(d->p, (d->max) * 2);
        d->max *= 2;
    }
    d->p[d->akt] = x;
    d->akt++;
}
void dyn_arr_min_add (struct DynArrayMin* d, int x)
{
    if ((d->akt)>(d->max) - 1)
    {
        d->p = (int*)realloc(d->p, (d->max) + 1);
        d->max++;
    }
    d->p[d->akt] = x;
    d->akt++;
}
void main()
{
    DynArray d;
    DynArrayMin e;
    int n, l, x,aa=0;
    scanf("%d", &n);
    d.max = n;
    d.p = (int*)malloc(sizeof(int)*n);
    e.max = n;
    e.p = (int*)malloc(sizeof(int)*n);
    do{
        printf("enter number\n");
        scanf("%d", &x);
        dyn_arr_add(&d, x);
        dyn_arr_min_add(&e, x);
        aa++;
        printf("want to enter another number; 0=no\n");
        scanf("%d", &l);
    } while (l != 0);
    for (int i = 0; i < aa;i++)
    printf("%d%d\n", d.p[i], e.p[i]);
    free(e.p);
    free(d.p);
    system("pause");
    return;
}

but starting with n = 5, which will be the initial size of the dynamically allocated arrays, and giving the numbers between 1 and 8 as an input, I was supposed to have an output like that: 11 22 33 44 55 66 77 88 but what i got was this pop-up messagethis pop-up message, and the following output after clicking "continue" in the pop-up message: 11 2-842203134 -33751037-33686019 -1414791683-1414812757 -1414812757-1414812757 66 77 88

1 Answer 1

2

You malloc number of ints, but realloc number of bytes.

On the first calls to realloc that will make the buffer smaller, instead of larger.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.