一个C语言程序运行时的问题
我这个程序一开始运行成功,但试了几次以后就突然运行时候失败了。我也觉得很奇怪,有人能帮忙看看吗。#include<stdio.h>
#include<stdlib.h>
struct hill
{int height;
int pass;
}*path;
int R,L;
int slide(int ,int);
int main()
{ int i,j,length,longest=0;
scanf("%d",&R);
scanf("%d",&L);
path = (struct hill*)malloc(sizeof(R*L*sizeof(struct hill)));
for(i=0;i<R;i++)
for(j=0;j<L;j++)
{scanf("%d",&((path+i*L+j)->height));
(path+i*L+j)->pass=0;
}
for(i=0;i<R;i++)
for(j=0;j<L;j++)
{ if((path+L*i+j)->pass)
length=(path+L*i+j)->pass;
else
length=slide(i,j);
if(length>longest)
longest=length;
}
free(path);
printf("%d",longest);
return 0;
}
int slide(int x,int y)
{ int i,temp,longest=0;
int d={{-1,0},{1,0},{0,-1},{0,1}};
for(i=0;i<4;i++)
{if(x+d<0 || x+d==R || y+d<0 || y+d==L)
continue;
if( (path+(x+d)*L+y+d)->height >= (path+x*L+y)->height)
continue;
if((path+(x+d)*L+y+d)->pass)
temp=(path+(x+d)*L+y+d)->pass;
else
temp=slide(x+d,y+d);
longest= temp>longest ? temp:longest;
}
(path+x*L+y)->pass=1+longest;
return 1+longest;
}
本帖最后由 人造人 于 2016-8-8 01:05 编辑
#include<stdio.h>
#include<stdlib.h>
struct hill
{
int height;
int pass;
}*path;
int R, L;
int slide(int x, int y)
{
int i, temp, longest = 0;
int d = { { -1,0 },{ 1,0 },{ 0,-1 },{ 0,1 } };
for(i = 0; i < 4; i++)
{
if(x + d < 0 || x + d == R || y + d < 0 || y + d == L)
continue;
if((path + (x + d)*L + y + d)->height >= (path + x*L + y)->height)
continue;
if((path + (x + d)*L + y + d)->pass)
temp = (path + (x + d)*L + y + d)->pass;
else
temp = slide(x + d, y + d);
longest = temp > longest ? temp : longest;
}
(path + x * L + y)->pass = 1 + longest;
return 1 + longest;
}
int main()
{
int i, j, length, longest = 0;
/*
scanf("%d", &R);
scanf("%d", &L);*/
struct test
{
int i;
int j;
};
i = sizeof(struct test);
i = sizeof(2 * 3 * sizeof(struct hill));
path = malloc(sizeof(R * L * sizeof(struct hill)));
for(i = 0; i < R; i++)
{
for(j = 0; j < L; j++)
{
scanf("%d", &((path + i * L + j)->height));
(path + i * L + j)->pass = 0;
}
}
/*
for(i = 0; i < R; i++)
{
for(j = 0; j < L; j++)
{
if((path + L * i + j)->pass)
length = (path + L*i + j)->pass;
else
length = slide(i, j);
if(length > longest)
longest = length;
}
}*/
free(path);
printf("%d", longest);
return 0;
}
只是找了一个问题,其它还没看
51 行 path = malloc(sizeof(R * L * sizeof(struct hill)));
你认为 sizeof(2 * 3 * sizeof(struct hill)) 应该是多少 人造人 发表于 2016-8-8 01:03
只是找了一个问题,其它还没看
51 行 path = malloc(sizeof(R * L * sizeof(struct hill)));
你认为 si ...
天哪。。。。太感谢了 一直没检查出来。。。 人造人 发表于 2016-8-8 01:03
只是找了一个问题,其它还没看
51 行 path = malloc(sizeof(R * L * sizeof(struct hill)));
你认为 si ...
天哪。。。。太感谢了 一直没检查出来。。。
页:
[1]