gpt4 book ai didi

c - 特定数组的大小

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:15 25 4
gpt4 key购买 nike

我有一个算法,可以显示两个数组是否相似。它有效,但我不知道数组的大小应该是多少。

例如:

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] 中输入多少数字才能确保该程序与大多数硬件兼容(我听说这也取决于内存。)

@更新1:

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

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;

你能帮我查一下吗?我找不到问题所在...

最佳答案

如果您不能(或不想)使用 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?

关于c - 特定数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41464404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com