저는 C로 초보자입니다. malloc() 함수를 사용하는 첫 번째 프로그램입니다. 이 함수를 사용할 때 문제가있을 수 있다고 생각합니다. 숫자 범위 (사용자 입력)에 대한 솔루션을 배치 할 배열 (사이클 길이)을 사용하고 싶습니다. 배열 크기는 사용자에 따라 다르므로 malloc()을 사용했습니다. 그러나 프로그램이 충돌하고 있습니다. 그런 다음free(cyclelength)
및 전화가 (또는 오히려, 메모리가가 지적 있음)를 가리키는 메모리를 액세스하는C 프로그램에서 malloc 함수가 제대로 작동하지 않습니다. 프로그램이 깨졌습니다.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x,y,num,count,p,k;
for(;;){
printf("enter first integer. must be between 1 and 100000\n");
scanf("%d", &x);
printf("enter second integer. must be between 1 and 100000. must not equal the first integer.\n");
scanf("%d", &y);
if(x>=1 && x<100000 && y>=1 && y<100000 && x!=y){
break;
}
else{
printf("try the whole process again\n");
}
}
if (x<y){
int j;
j=y;
y=x;
x=j;
} //making x always greater than y
int *cyclelength=malloc(5000*sizeof(int));
if (NULL==cyclelength){
printf("process aborted");
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
count=0;
cyclelength[count]=p;
num+=1;
count+=1;
}
free(cyclelength);
cyclelength=NULL;
}
int c=0;
int max=cyclelength[c];
for(;c<x-y;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
printf("%d,%d,%d",x,y,max);
return 0;
}
질문과 함께 충돌 결과를 게시해야합니다. 더 나은 답변을 빨리 얻을 수 있습니다. – cytinus