2017-10-20 44 views
-1

我是C启动者,刚刚学习编程的基础。当我练习编码时,我注意到意外输出有些奇怪,我不知道它的原因,甚至无法描述问题所在。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 

我最初想到的是,阵列[7]应该给我阵列[7] = 8的输出,因为数字“8”是用户键入的内容。但是,它变成了随机数。我想知道原因。

+2

'INT X = 1; int array [x];' - 当你创建它时,你的数组有多大?稍后改变'x'不会让你的数组神奇地成长。 –

回答

3
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(),并确保阅读the manpage,以便利用所有可能性来检测错误。


*)请注意您使用这里的功能被称为可变长度数组(VLA),但这个词“变量”仅仅意味着数组的大小不是编译期时间常数。它确实是而不是意味着一旦阵列存在就可以改变大小 - 这将是一个动态数组,您必须使用C实现自己(使用malloc()realloc())。

另请注意VLA尽管非常普遍,但不支持,C11使它们成为可选功能。如果没有可用的沃拉斯做,你必须使用一个固定大小的数组足够大,还是分配自己使用malloc()您的阵列,在这种情况下,它看起来像

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

不要忘记检查arrayNULL当你这样做时,当你完成它时不要忘记free(array);

1

咦?

当你这样做:

int x = 1; 
int array[x]; 

你得到一个1个元素的数组称为array。稍后更改x的值不会奇迹般地调整数组的大小。在得到合适的值x后,将array[x]声明

并添加对I/O调用的检查,它们可能会失败。

0
int x = 1; 
int array[x]; 

它限制了数组的大小。不要这样做。

0

什么?

int x = 1; 
    int array[x]; 

    // ..... 

    x = atoi(input); 

你真的expext是到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); 
     } 
    } 
相关问题