好的,
我被卡住了。我有一个程序代码,可以根据算法系统地执行站在圆圈中的人,但是我遇到了一个问题,它在发布模式下崩溃了。如果我使用调试器(codeblocks)运行代码,它可以正常运行,但是如果不用它就会崩溃。我在网上查找,唯一找到的是未初始化变量,但是我尝试在声明时立即为变量设置值,但它并没有解决问题。
如果有人能看到我的问题,我将非常感激帮助。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// if the program does not work, please run in debugger mode. It will work.
void remove_person(int** array, int arraySize, int position)
{
int i;
for (i = 0; i < arraySize; ++i)
printf("%d ", (*array)[i]);
printf("\n");
int* temp = malloc((arraySize - 1) * sizeof(int)); // create temporary array smaller by one element
memmove(temp,*array,(position+1)*sizeof(int)); // copy entire array before position
memmove(temp+position,(*array)+(position+1),(arraySize - position)*sizeof(int)); // copy entire array after postion
for (i = 0; i < arraySize - 1; ++i)
printf("%d ", (temp)[i]);
printf("\n");
free (*array);
*array = temp;
}
int kill(int** a, int n)
{
int pos = 0;
int round = 1;
while(n > 1)
{
pos = pos + 2 - (round % 2);
while(pos >= n)
pos = pos - n;
remove_person(a,n,pos);
n--;
while(pos >= n)
pos = pos - n;
round++;
}
return *a[0];
}
void main()
{
int n, survivor, i;
int* people;
printf("Enter number of people for Russian Roulette: \n");
scanf("%d", &n);
people = (int*) malloc(n*sizeof(int));
for(i=0; i < n; i++)
{
people[i] = i;
}
survivor = kill(&people, n);
printf("The survivor is person #%d\n", survivor);
}
void main
是非标准用法。 - chrisfree()
函数并修改前一个元素的next
指针。 - Eddy_Emvoid main
。我不知道Stroustrup(他应该是规范的大师)是如何错过这一点的。我相信自C89以来就允许使用void main
。(此外,标准基本上允许任何返回类型,甚至像float main
或struct foo main
这样愚蠢的东西)。 - nneonneomemmove
,我是正确的。哎呀。我没看到你的答案。 - Eddy_Em