C++ 执行桶排序时出错
这是我的代码,我无法理解错误在哪里C++ 执行桶排序时出错,c++,sorting,data-structures,bucket,C++,Sorting,Data Structures,Bucket,这是我的代码,我无法理解错误在哪里 #include <iostream> #include<iomanip> using namespace std; #define narray 8;// array size; #define nbucket 5;// bucket size; #define interval 10;// bucket range struct node { int data; struct node *next; }; void BucketS
#include <iostream>
#include<iomanip>
using namespace std;
#define narray 8;// array size;
#define nbucket 5;// bucket size;
#define interval 10;// bucket range
struct node
{
int data;
struct node *next;
};
void BucketSort(int arr[]);
struct node *InsertionSort(struct Node *list);
void print(int arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(int value);
void BucketSort(int arr[])
{
int i,j;
struct node **buckets;
buckets = (struct node **)malloc(sizeof(struct node*) * nbucket);
for (i=0;i<nbucket;i++){
buckets[i]=NULL;
}
for (int i=0;i<narray;i++){
struct node *current;
int pos=getBucketIndex(arr[i]);
current=(struct node *)malloc(sizeof(struct node));
current->data=arr[i];
current->next=buckets[pos];
buckets[pos]=current;
}
}
int main(){
return 0;
}
删除
代码>来自#定义nbucket 5代码>和其他定义
此时,预处理器将第22行扩展为明显无效的:
buckets = (struct node **)malloc(sizeof(struct node*) * 5;);
// ^^
#define
行不是编译器的一部分,而是在编译器之前运行的一部分。预处理器处理的行不应以分号结尾
以这一行为例:
#define narray 8;// array size;
这将创建一个名为narray
的宏。当预处理器运行时,它用替换文本替换所有narray
,在本例中为8代码>。如你所见,拥有8代码>在表达式中,将在不应有分号的地方添加分号。谢谢@Henrik,但这可以在不进行向下投票的情况下完成。此外,完全失去#defines。首选const int nbucket=5很遗憾,在使用模板时出现15页长的错误时,我没有使用Stackoverflow。否则,我就可以用编译错误登录站点。至少在调试之前尝试跟踪编译器指令,然后在问题被否决之前请求帮助一个额外的注释:这是C++,因此丢失多余的“结构”关键字。您需要使用“struct”来声明结构,但在此之后将其称为节点
,节点*
,节点**
,而不是结构节点*
,结构节点**
#define narray 8;// array size;