簡體   English   中英

錯誤:下標值既不是數組也不是指針

[英]error: subscripted value is neither array nor pointer

int get_first(int arr[],int count)
{

   int half = count / 2;

   int *firstHalf = malloc(half * sizeof(int));
   memcpy(firstHalf, arr, half * sizeof(int));
   return firstHalf;
}

int get_second(int arr[], int count)
{
    int half = count / 2;

    int *secondHalf = malloc(half * sizeof(int));
    memcpy(secondHalf, arr + half , half * sizeof(int));
    return secondHalf;
}

int result = get_first(arr, count);
int size = sizeof(result) / sizeof(result[0]);

我正在編寫一個將數組拆分為兩個相等部分的函數。 該函數接受一個數組和數組的大小。 我通過將數組的前半部分存儲在結果中並打印其長度來測試該功能。 但是當我構建函數時,

int size = sizeof(result) / sizeof(result[0]);

給出錯誤提示“錯誤:下標值既不是數組也不是指針”

是因為我的函數無法將數組的前半部分傳遞給結果嗎? 還是存儲數組的方式錯誤? 如果是這樣,我如何拆分陣列,有人可以幫助我修復它嗎? 提前致謝。

我可以看到兩個問題:

  1. 在函數int get_first(int arr[],int count)int get_second(int arr[], int count)您將返回int指針,但函數的返回類型為int。
  2. result被聲明為int,但是您像result [0]一樣訪問它。

從上面的點1可以明顯看出對1的校正。 更正2:

代替:

int result = get_first(arr, count);

您應該寫:

int *result = get_first(arr, count);

希望這可以幫助。

暫無
暫無

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

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