[英]2D allocated array (fixed number of columns) as return value of a function
我想要一些有關指針的幫助:在主函數中,我已初始化了應指向數組的變量:
int main() {
int n;
double (*array)[3];
array = fillArray(&n);
該函數接收一個整數參數,該參數對行數進行計數。 函數的返回值應該是指向新創建的數組的指針,該指針將保存到主函數中的變量“ array”中:
double (*)[3] fillArray(int * n) {
double (*array)[3] = NULL;
int allocated = 0;
*n = 0;
while (1)
{
/*scanning input*/
if (allocated <= *n)
{
allocated += 10;
array = (double(*)[3]) realloc (array, sizeof(*array) * allocated)
}
array[*n][0] = value1;
array[*n][1] = value2;
array[*n][2] = value3;
(*n)++;
}
return array;
}
但是,返回值的類型不正確,我有點迷茫。 誰能告訴我這段代碼有什么問題嗎?
先感謝您 :)
您的代碼有一個不相關的語法錯誤和一些未聲明的變量,但是您詢問的問題與fillArray()
函數的聲明形式有關。 此替代方法對我有效:
double (*fillArray(int * n))[3] {
double (*array)[3] = NULL;
/* ... */
return array;
}
注意形式上與相同類型變量的聲明相似。
問題是,盡管double (*)[3]
是在轉換中使用的完全有效的類型指示符,但是在嘗試聲明對象的類型時完全使用它是不正確的。
對問題中未提及的項目給出一些猜測。
我認為這就是您想要的。
注意檢查對realloc()
的調用是否成功
注意magic
數字的#define
#include <stdlib.h> // realloc(), exit(), EXIT_FAILURE
#define ALLOCATION_INCREMENT (10)
#define NUM_DOUBLES (3)
struct tagArray
{
double arrayEntry[ NUM_DOUBLES ];
};
struct tagArray *fillArray(int *n);
int main( void )
{
int n = 0;
struct tagArray *array;
if( NULL == (array = fillArray(&n) ) )
{ // then array generation failed
exit( EXIT_FAILURE );
}
// implied else, array generation successful
....
free( array );
return 0;
} // end function: main
struct tagArray *fillArray(int *n)
{
struct tagArray *array = NULL;
int allocated =0;
while( 1 )
{
/* scanning input,
* to acquire 'value1, value2, value3'
* with some key input causes execution of 'break;'
* */
if( allocated <= *n )
{
allocated += ALLOCATION_INCREMENT;
struct tagArray *temp = realloc (array, sizeof( struct tagArray) * allocated );
if( !temp )
{ // then realloc failed
free( array );
return( NULL );
}
array = temp;
}
array[*n][0] = value1;
array[*n][1] = value2;
array[*n][2] = value3;
(*n)++;
}
return array;
} // end function: fillArray
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.