簡體   English   中英

如何在C中連接兩個動態int數組?

[英]How can I concat two dynamic int-arrays in C?

我的問題是將兩個動態分配的int數組合並為其中一個。 我想從邏輯上講它應該起作用...

我建議函數內的realloc(...)是錯誤的。 我也在功能之外嘗試了它,但是它也不起作用。

void concatArrays(int *numbers1, int length1, int *numbers2, int length2)
{
  numbers1 = realloc(numbers1, (length1+length2) * sizeof(int));

  int counter = 0;
  for(int i = length1; i<(length1+length2); i++)
  {
    numbers1[i] = numbers2[counter];
    counter++;
  }
}

現在在main() ,我填充了兩個數組,至少我要打印出更長的新數組(numbers1)。

int main()
{
  int length1 = 5;
  int *numbers1 = malloc(length1 * sizeof(int));

  // fill array1
  . . .

  int length2 = 4;
  int *numbers2 = malloc(length2 *sizeof(int));

  // fill array2
  . . .

  concatArrays(numbers1, length1, numbers2, length2);


  // print out "new" array (numbers1)
  int new_len = length1 + length2;
  for(int i = 0; i<new_len; i++)
  {
    printf("%d ", numbers1[i]);
  }

  free(numbers1);
  free(numbers2);
}

謝謝您提前提出所有建議!

realloc()通常會返回一個新的指針,除非新的大小僅稍大一些並且可以容納在一個過度分配的數組中。 您沒有將新的指針“ numbers1”傳遞回調用函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM