簡體   English   中英

C代碼-為什么輸出在我的代碼中返回意外值?

[英]C code - Why the output returned unexpected value in my code?

我是C入門者,剛剛學習了編程的基礎。 當我練習編碼時,我注意到意外輸出有些奇怪,我不知道其原因,甚至無法描述問題所在。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main()
{
  int numberEntered = 0;
  int index = 0;
  char input[32];
  int TotalNum = 0;
  int x = 1;
  int array[x];

  printf("Please enter the size of the array: ");
  fgets(input,32,stdin);
  x = atoi(input);

  for(index =0; index < x; index++)
  {
      printf("\nPlease enter your number:");
      fgets(input,32,stdin);

      numberEntered = atoi(input);
      printf("The number you entered is : %d\n",numberEntered);


      array[index] = numberEntered;

      TotalNum ++;
   }

  for(index = 0; index < TotalNum; index++)
  {
      printf("array[%d] = %d\n",index,array[index]);
  }
    return 0;
}

當用戶輸入x = 15時; 然后用戶輸入1到15之間的數字; 輸出為:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
array[5] = 6
array[6] = 7
array[7] = 668977
array[8] = 9
array[9] = 10
array[10] = 11
array[11] = 12
array[12] = 13
array[13] = 14
array[14] = 15

我最初希望array [7]應該給我array [7] = 8的輸出,因為用戶鍵入的是數字“ 8”。 但是,它更改為隨機數。 我想知道原因。

int x = 1;
int array[x];

printf("Please enter the size of the array: ");
fgets(input,32,stdin);
x = atoi(input);

這行更改x的值,但不更改array的大小。 您只能在聲明數組時為其指定大小。 *)

重新排序為以下內容:

printf("Please enter the size of the array: ");
fgets(input,32,stdin);
int x = atoi(input);
int array[x];

附帶說明一下, atoi()不適用於檢查錯誤(您應該在交互式輸入中執行此操作)。 請改用strtol() ,並確保閱讀聯機幫助頁 ,以便您利用所有可能的方法來檢測錯誤。


*)請注意,您在此處使用的功能稱為可變長度數組 (VLA),但是“ 變量 ”一詞僅表示數組的大小不是編譯時常量 並不意味着,一旦數組存在,你可以改變大小-這將是(使用動態數組 ,你必須實現自己用C malloc()realloc()

還要注意沃拉斯,雖然很普遍, 沒有得到支持,C11使得它們的可選功能。 如果沒有可用的VLA,則必須使用足夠大的固定大小的數組,或者使用malloc()自己分配數組,在這種情況下,它看起來像

int x = atoi(input);
int *array = malloc(x * sizeof *array);

執行此操作時,不要忘記檢查array是否為NULL ,也不要忘記free(array); 完成后。

??

執行此操作時:

int x = 1;
int array[x];

您將得到一個稱為array的1元素array 稍后更改x的值不會神奇地調整數組的大小。 得到x的正確值 ,放置array[x]聲明。

並添加檢查的I / O調用,它們可能會失敗。

int x = 1;
int array[x];

它限制了陣列的大小。 不要這樣。

什么?

  int x = 1;
  int array[x];

  // .....

  x = atoi(input);

您是否真的擴展了將新值分配給x變量的大小,調整已經聲明的array變量的大小

不,您必須在知道數組大小時聲明該數組。

  int x;

  // .....

  x = atoi(input);

  int array[x];

或者,甚至更好的是,從堆中分配一個新數組,尤其是。 x是會得到很大的價值有一天...

  int arraylength;

  // .....

  arraylength = atoi(input);

  if (arraylength > 0)     // sanity check
  {
      int* array = malloc (arraylength * sizeof(int));
      if (array != NULL)   // allocation succeeded
      {
          // use array[i]...

          // and relese the array when no longer needed
          free (array);
      }
  }

暫無
暫無

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

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