I am writing a program to compute the fastest/shortest path between locations (stored in a directed graph represented by an adjacency list). I am trying to create this adjacency list ("al") as an array of pointers to Vertex class objects, but I get the error " 'al' was not declared in this scope". Any suggestions on where I should create the adjacency list to avoid scope problems would be greatly appreciated.

Description of the files:

  • main.cpp - Reads in input files
  • vertex.cpp and vertex.h - Define the Vertex class
  • segment.cpp and segment.h - Define the Segment class
  • locations.txt - Input file containing the number and names of locations, each of which should be a vertex
  • segments.txt - Input file containing information about the segments connecting the vertices. Each line has four values: vertex number where segment begins, vertex number where segment ends, distance of segment, traffic speed on segment
  • trips.txt - Trip requests

The text files must be input to the program in this order: locations.txt segments.txt trips.txt

You didn't include <string> header in main.cpp (for std::getline declaration). Change "iostream" and "fstream" to <iostream> and <fstream> (standard headers).

You declare al variable in the if alternative block. Of course, this local variable is out of scope outside this block. Declare al at the main function body level - that's all.

Now you have:

if (numLocations == 0)
  { // it's a new scope
    Vertex ** al; // al is local in if alternative
    al = new Vertex * [numLocations]; // to breath al's last
  } // al is out of scope and is discarded.
  // and you have memory leak because can't free this memory

Thanks a lot, ArkM! So even though the line

al = new Vertex * [numLocations];

is declared on a local level, I can still free the memory from outside that level?

You can deallocate dynamically allocated memory here, there and everywhere:

int main()
{
  al = new Vertex*[numLocations];
  ...
  delete [] al; // al is visible
  ...
  // or
  f(al); // al as argument
  ...
}
...
void f(Vertex* p)
{
  delete [] p; // array of Vertex is deallocated
  ...
}

Name scope (name visibility) and storage duration (span of life) are different notions. In actual fact to deallocate memory obtained from operator new you need not al variable per se but the pointer value which refers to the memory chunk.

commented: helpful, clear, concise +1

Ok. Thanks a lot for explaining that to me!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.