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;
}
}
This:
should be:
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.Note the
forloop does not assign a value to the first element inrow_valueorcol_value:as it starts at index
1and the assignments within theforshould be: