2017-01-04 63 views
0

我有一个算法,它应该显示两个数组是否相似。它的作品,但我不知道什么大小应该是阵列。特定数组的大小

例如:

int a[10], i = 0, r = 0, n = 0; 
printf("Enter the amount of numbers in arrays: "; 
scanf("%d", &n); 

printf("Enter the numbers of array: "; 
for (i = 0; i < n; i++) 
{ 
    scanf("%d", &a[i]); 
} 

如果我为输入 “n” 的变量n = 11,程序停止在终点。我的问题是:我应该把对数组a [THAT_PLACE],以确保这一计划将与大多数硬件兼容(我听说,这也从内存中视)

@ UPDATE1什么号码:

我选择了一个alk's解决方案。但它仍然不起作用。这里是我的代码:

int main() 
{ 

int i = 0, temp_a = 0, switch_a = 0, temp_b = 0, switch_b = 0, n = 0; 

printf("Enter the amount of numbers in arrays: "); 
scanf("%d", &n); 
{ 
    int a[n], b[n]; 
    printf("Enter elements of first array: "); 
    for (i = 0; i < n; ++i) 
    { 
     scanf("%d", &a[i]); 
    } 
    printf("Enter elements of second array: "); 
    for (i = 0; i < n; ++i) 
    { 
     scanf("%d", &b[i]); 
    } 
    do 
    { 
     switch_a = 0; 
     for (i = 0; i < n - 1; i++) 
     { 
      if (a[i] > a[i + 1]) 
      { 
       switch_a = switch_a + 1; 
       temp_a = a[i]; 
       a[i] = a[i + 1]; 
       a[i + 1] = temp_a; 
      } 
     } 
    } while (switch_a != 0); 
    //bubble sort 
    do 
    { 
     switch_b = 0; 
     for (i = 0; i < n - 1; i++) 
     { 
      if (b[i] > b[i + 1]) 
      { 
       switch_b = switch_b + 1; 
       temp_b = b[i]; 
       b[i] = b[i + 1]; 
       b[i + 1] = temp_b; 
      } 
     } 
    } while (switch_b != 0); 
    //Cheks, if an arrays are the same. 
    for (i = 0; i < n; i++) 
    { 
     if (a[i] != b[i]) 
     { 
      printf("This two arrays don't have the same elements.\n\n\n"); 
      return 0; 
     } 
    } 

    printf("This two arrays have the same elements.\n\n\n"); 
} 

return 0; 

}

你能检查一下吗?我找不到有什么问题...

+0

你想要一个变量长度阵列,幸运的是C99开始。在声明'int a [n];' –

+0

“之前,请先阅读scanf行所需的元素数量......”该程序将与大多数硬件兼容“ - 不应该编写程序以使其适用于**问题**它是为了解决? – Olaf

+0

如果添加'#include ',更新后的代码似乎可以正常工作。问题是什么?此外,这听起来像一个新的问题,与旧的问题无关。如果您可以识别问题,可能会发布一个新问题? –

回答

2

您的阵列a只能包含10个int's。所以,如果你输入n为11,那么你有undefined behaviour由于越界访问。

您可以使用C99 VLA(可变长度数组)或使用malloc()系列函数使用动态内存分配。

注意:VLA在C11中是可选的。因此,您可能需要使用宏__STDC_NO_VLA__来检查您的实现是否不支持它。

一个潜在的问题与VLA(有自动存储时间 - 俗称“堆栈”)是很难弄清楚,如果分配是成功的大型阵列。

1

如果在使用你的C实现支持变长数组,然后就去做:

int i = 0, r = 0, n = 0; 
printf("Enter the amount of numbers in arrays: "; 
scanf("%d", &n); 

{ 
    int a[n]; 
    printf("Enter the numbers of array: "; 
    for (i = 0; i < n; i++) 
    { 
    scanf("%d", &a[i]); 
    ... 
2

如果你不能(或者不想)使用VLA,使用malloc:man malloc

例子:

int *buffer; 
int dim; 

printf("Enter the amount of numbers in arrays: "); 
scanf("%d", &dim); 
buffer = (int*) malloc(sizeof(int) * dim); 
if (buffer == NULL) { 
    perror("Malloc error"); 
    exit(-1); 
} 

更多关于这里的malloc:Stack Overflow: How do malloc() and free() work?