malloc was not declared in this scope
红色的地方编译有错误,不知道哪里有问题#include <stdio.h>
#define MAXSIZE 5
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode{
ElementType data;
Position Last;/*保存数组Data[]中最后一个元素的位置*/
};
Position BinarySearch(List, ElementType);
int main()
{
List L;
L = (List)malloc(sizeof(struct LNode));
L->data = {12, 31, 55, 89, 101};
L->Last = sizeof(L->data);
ElementType X = 31;
Position ret;
ret = BinarySearch(L, X);
printf("%d is %d", X, ret);
return 0;
}
Position BinarySearch(List L, ElementType X)
{
Position Left, Right, Mid;
Left = 1;
Right = L->Last;
while(Left <= Right)
{
Mid = (Left + Right) / 2;
if(L->data > X)
Right = Mid - 1;
else if(L->data < X)
Left = Mid + 1;
else
return Mid;
}
} 本帖最后由 superbe 于 2019-12-13 22:33 编辑
少头文件了吧#include <malloc.h>
BinarySearch的逻辑有点问题,修改的代码:
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 5
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType data;
Position Last;
};
Position BinarySearch(List, ElementType);
int main()
{
List L;
L = (List)malloc(sizeof(struct LNode));
//L->data = { 12, 31, 55, 89, 101 };
L->data = 12;
L->data = 31;
L->data = 55;
L->data = 89;
L->data = 101;
L->Last = sizeof(L->data) / sizeof(ElementType);
ElementType X = 31;
Position ret;
ret = BinarySearch(L, X);
(ret > 0) ? printf("%d is %d\n", X, ret) : printf("Not found\n");
return 0;
}
Position BinarySearch(List L, ElementType X)
{
Position Left, Right, Mid;
Left = 1;
Right = L->Last;
while (Left <= Right)
{
Mid = (Left + Right) / 2;
if (L->data == X)
return Mid;
if (L->data > X)
Right = Mid - 1;
else if (L->data < X)
Left = Mid + 1;
}
return -1;
}
页:
[1]