【发布时间】:2013-03-28 10:24:13
【问题描述】:
好的,
所以我被困在这里。我有一个程序的代码,该程序根据算法系统地执行站成一圈的人,但我遇到了它在发布模式下崩溃的问题。如果我使用调试器(代码块)运行它,我的代码运行良好,但如果我不这样做,它就会崩溃。我在网上环顾四周,唯一发现的是未初始化的变量,但我尝试在声明时立即为变量设置值,但并没有解决问题。
如果有人能看到我的问题,我将不胜感激。
#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是非标准的。 -
你不认为一个简单的列表会比这个解决方案漂亮吗?要从列表中删除元素,您只需
free()它并修改前一个元素的next指针。 -
@chris:推荐阅读:homepage.ntlworld.com/jonathan.deboynepollard/FGA/…。 tl;dr:
void main()被 C99 标准以实现定义的方式允许。 -
@nneonneo,然后为this 感到羞耻。也许它专注于早期的标准。
-
@chris: Stroustrup 错了。阅读规范:c0x.coding-guidelines.com/5.1.2.2.1.html。注意“或等效的行;或以一些其他实现定义的方式。”
标签: c debugging crash release codeblocks