我有一個用c編寫的代碼。我有一個int指針,並將其傳遞給一個函數。該函數分配內存並填充數組,然後返回。基本上看起來是這樣的:如何在C中動態創建一個函數列表#
main()
{
int* array;
function(&array);
}
void function(int** array)
{
int size = 25;
*array = malloc(size);
(*array)[0] = 42;
}
尺寸在主體中是未知的。我如何在C#中執行此操作?我嘗試了List,但我無法使它工作。我已經嘗試了列表和ref列表,並且它們都給索引超出範圍。
編輯:
這工作得很好
class Program
{
static void function(List<int> array)
{
array.Add(42);
}
static void Main(string[] args)
{
List<int> array = new List<int>();
function(array);
}
}
而這其中也
class Program
{
static void function(out int[] array)
{
array = new int[25];
array[0] = 42;
}
static void Main(string[] args)
{
int[] array;
function(out array);
}
}
但下面拋出一個異常
class Program
{
static void function(out List<int> array)
{
array = new List<int>(25);
array[0] = 42;
}
static void Main(string[] args)
{
List<int> array;
function(out array);
}
}
_「我嘗試過使用List,但是我無法使它工作。」_您的嘗試在哪裏? – JLRishe
「list」引發的錯誤是什麼,因爲我沒有看到/預防列表使用相同/相似方式的任何問題。 – Jaya
請告訴我們你已經嘗試了什麼。 – ja72