Search code examples
cmallocrealloc

How to allocate memory in this case?


I have pointers in main for which I don't know it's size. A function returns this pointer to main. Inside the function I can calulate the size of pointer and hence need to store values in them and return them to main. How to modify/allocate memory in this case.

int main()
{
    int *row_value, *col_value;
    col_row_value(row_value,col_value);
    ...
    return(0);
}

void col_row_value(row_value,col_value)
{
    // how to allocate/modify memory for row_value and col_value and store data
    // for example would like to allocate memory here
    int i;
    for(i=0;i<10;i++) {
        row_value[i]=i;
        col_value[i]=i;
    }
}

I tried something like this,it doesn't work

int main()
{
    int *row_value, *col_value;
    row_value=NULL;
    col_value=NULL;
    col_row_value(&row_value,&col_value);
    ...
    return(0);
}

void col_row_value(int **row_value,int **col_value)
{
    // how to allocate/modify memory for row_value and col_value and store data
    // for example would like to allocate memory here
    int i;
    *row_value=(int*)realloc(*row_value,10*sizeof(int));
    *col_value=(int*)realloc(*col_value,10*sizeof(int));
    for(i=0;i<10;i++) {
        row_value[i]=i;
        col_value[i]=i;
    }
}

Solution

  • This:

    *row_value=(int*)realloc(row_value*,10*sizeof(int));
    

    should be:

    *row_value = realloc(*row_value,10*sizeof(int));
                     /** ^ **/
    

    Note the cast is unnecessary. Assign the result of realloc() to a temporary pointer in case the reallocation fails which would mean the original memory would be inaccessible.

    int* tmp = realloc(*row_value, 10 * sizeof(*tmp));
    if (tmp)
    {
        *row_value = tmp;
    }
    

    Note the for loop does not assign a value to the first element in row_value or col_value:

    for(i=1;i<10;i++)
    

    as it starts at index 1 and the assignments within the for should be:

    (*row_value)[i] = i;
    (*col_value)[i] = i;