我有主指针,我不知道它的大小。一个函数将这个指针返回给main。在函数内部,我可以计算指针的大小,因此需要在其中存储值并将它们返回给main。在这种情况下如何修改/分配内存。如何在这种情况下分配内存?
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;
}
}
我想这样的事情,这是行不通的
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;
}
}
程序设计:为什么使用变量的代码不知道它们的大小?为什么你想要一个只关心设置值的函数来完成一个完全不同的任务,即动态内存分配?你为什么不能从调用者那里做到这一点? – Lundin
纯粹作为利益的问题,你为什么离开位置0不变? –
我不知道这是否是这种情况,但总的来说,您最好在col_row_vaule中返回分配字段的大小。 –