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
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));
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;
精彩评论