【发布时间】:2019-04-17 09:41:57
【问题描述】:
我正在尝试通过制作一个冒泡排序程序来练习 C 语言。到目前为止的问题似乎是,在不再满足条件后,为数组的单元格赋值的 for 循环被卡住了,但它似乎没有执行循环中的命令。我不知道到底发生了什么,我添加了一些额外的行来看看发生了什么,这些是我的结论。代码如下:
#include <stdio.h>
#include <stdlib.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int *sort(int *array)
{
int finish = 1;
while (finish = 1)
{
finish = 0;
for (int i = 0; i <= sizeof(array); i++)
{
if ((array + i) > (array + i + 1))
{
swap(array + i, array + i + 1);
finish = 1;
}
}
}
return array;
}
int main()
{
int s, res;
printf("Give me the size of the array being sorted(larger than 1) : ");
do
{
res = scanf("%d", &s);
if (res != 1)
{
printf("Wrong Input!\n");
exit(1);
}
if (s < 2)
printf("Only numbers equal or larger than 2\n");
} while (s < 2);
int array[s];
for (int i = 0; i < s; i += 1)
{
scanf("%d", array + i);
printf("%d %d %d\n\n", *(array + i), i, i < s); // I used this to check if my values were ok
}
printf("end of reading the array"); //I added this line to see if I would exit the for loop. I am not seeing this message
sort(array);
printf("\n");
for (int i = 0; i < sizeof(array); i++)
printf("%d\n\n", array + i);
printf("Array has been sorted! Have a nice day!\n\n************************************************************");
return 0;
}
【问题讨论】:
-
sizeof(array)不会像您认为的那样做。查找“数组到指针衰减”。 -
还有
while (finish = 1)-->while (finish == 1) -
@Swordfish 我认为
int array[s];应该是一个数组....对吗? -
请始终在编译器中启用警告。
while (finish = 1)行应该引起一些关于条件中的赋值的警告。 -
sizeof(array)两次都被误用。在sort()函数中,sizeof(array)返回构成指针int *array的字节数。在main中,sizeof(array)返回数组int array[s];中的字节 数,而不是数组中的元素数。
标签: c arrays loops for-loop scanf