0

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

1
  • BTW , i have to return the counter and not the array Commented Aug 21, 2011 at 13:56

2 Answers 2

4

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));
Sign up to request clarification or add additional context in comments.

1 Comment

i tried that but when i failed when i tried to assign into it
2

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;

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.