【发布时间】:2012-09-07 07:35:18
【问题描述】:
我在 main 中有指针,但我不知道它的大小。一个函数将此指针返回给 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;
}
}
【问题讨论】:
-
程序设计方面:为什么使用变量的代码不知道它们的大小?为什么你想要一个只关心设置值的函数也做一个完全不同的任务,即动态内存分配?为什么你不能从调用者那里做到这一点?
-
纯粹出于兴趣,你为什么不改动位置 0?
-
我不知道是否是这种情况,但总的来说,最好在 col_row_vaule 中返回分配字段的大小。
-
在许多情况下,我们不会知道数组的确切大小。举个简单的矩阵-矩阵乘法例子,我们不知道乘积的非零元素。