0

目标: 遍历structvertices中的内存块。Heap

错误:expected unqualified-id before ‘(’ token在尝试访问vertices. 另外,‘vertices’ was not declared in this scope.

标题:

typedef struct Heap *PriorityQueue_t;
typedef struct HeapItem *PriorityItem_t;

PriorityQueue_t Init(int max_capacity, int source_vertex);

执行:

#include "heap.h"
#include <stdlib.h>
#include <limits.h>

struct Heap
{
  int size;
  PriorityItem_t vertices;
};

struct HeapItem
{
  int id;
  int distance;
};

PriorityQueue_t Init(int max_capacity, int source_vertex)
{
  PriorityQueue_t Q;

  Q = (PriorityQueue_t)malloc(sizeof(PriorityQueue_t));
  Q->vertices = (PriorityItem_t)malloc(sizeof(PriorityItem_t)*max_capacity);

  Q->size = max_capacity;

  int i;
  for(i = 0; i < Q->size; i++)
  {
    Q->(vertices + i)->id = i; //Errors on this line.
    Q->(vertices + i)->distance = INT_MAX;
  }
  Q->(vertices + source_vertex)->distance = 0;

  return Q;
}
4

3 回答 3

2

您将括号放在错误的位置。尝试这个:

    (Q->vertices + i)->id = i; //Errors on this line.
    (Q->vertices + i)->distance = INT_MAX;
  }
  (Q->vertices + source_vertex)->distance = 0;
于 2013-04-20T03:10:41.943 回答
1
Q->(vertices + i)->id = i; //Errors on this line.
Q->(vertices + i)->distance = INT_MAX;
Q->(vertices + source_vertex)->distance = 0;

你不能那样做...

Q->vertices[i].id = i;
(Q->vertices + i)->distance = INT_MAX;
(*(Q->vertices + source_vertex)).distance = 0;  // Not sensible, but legal
于 2013-04-20T03:12:19.390 回答
0

您可以通过使用普通索引和删除强制转换来避免大量括号:

PriorityQueue_t Init(int max_capacity, int source_vertex)
{
  PriorityQueue_t Q;

  Q = malloc(sizeof *Q);
  Q->vertices = malloc(max_capacity * sizeof *Q->vertices);

  Q->size = max_capacity;

  int i;
  for(i = 0; i < Q->size; i++)
  {
    Q->vertices[i].id = i;
    Q->vertices[i].distance = INT_MAX;
  }
  // maybe add next line: 
  // assert (source_vertex >=0 && source_vertex < Q->size);
  Q->vertices[source_vertex].distance = 0;

  return Q;
}
于 2013-04-20T14:45:20.200 回答