DoronS
DoronS

Reputation: 347

realloc array inside a function

i try to reallocate array inside a function.

unsigned findShlasa(int matrix[COL_MATRIX_A][ROW_MATRIX_A], Sa *ar, list head)
{
Node* current_pos;
unsigned count = 0;
unsigned row_index, col_index;


for (col_index = 0; col_index < COL_MATRIX_A; col_index++)
{
    for (row_index = 0; row_index < ROW_MATRIX_A; row_index++)
    {
        if ((row_index + col_index) == matrix[col_index][row_index])
        {
            if (!head)
            {
                ar = (Sa*) malloc(sizeof(Shlasha));
                head = (list) malloc(sizeof(list));
                current_pos = head;
                count++;
            }
            else
            {
                count++;
                ar = (Sa*) realloc(ar, count * sizeof(Shlasha));
                current_pos->next = (Node*) malloc(sizeof(Node));
            }
.....

when i try to print the array outside this function it doesn't work because ar now point to other place in the memory. how can i reallocate it inside the function and still point to the same place outside the function?

P.S: Sa* is pointer to struct

Upvotes: 0

Views: 3251

Answers (2)

shelleybutterfly
shelleybutterfly

Reputation: 3247

You are just modifying the function's local copy of the array because it's a single pointer. To return it outside the array you could pass Sa **ar and then take the address of the pointer you're passing into the function, and, then, in your function wherever you have ar change it to *ar.

You could also pass in something like Sa **array and then assign to a local variable if you want to avoid changing the code, so

Sa *ar = *array;

then you could still use

ar = (Sa*) malloc(sizeof(Shlasha));

then at the end of the function before you return do:

*array = ar;

Upvotes: 2

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

Pass it as a double pointer to be able to modify the address itself:

..., Sa **ar, list head)

and then

*ar = (Sa*) realloc(*ar, count * sizeof(Shlasha));

Upvotes: 4

Related Questions