Open main menu

CDOT Wiki β

Changes

C/C++ FAQ

9,101 bytes added, 22:56, 24 September 2013
C/C++ FAQ
function will it call when the pointer is dereferenced and why?
Q: How to redirect cerr to a file (instead of a console window)?
Q: How to visualize a multi-dimensional array? <br>Q: What is the correct way to pass a 2D array (called array) into a function? Which of the following is right: array[][], array[][COLS] or **array?Q: When creating the header file for a template class and putting the implementation in the header as well there are no errors. However when splitting the deceleration (header) and implementation (making a cpp file) for that class template there are numerous compile errors. What do all these errors mean?Q: Can Stacks, Queues or Lists be referenced using indexes?Q: How to get size of an array without storing the size anywhere? Q: How do you get the length of a file / read the entire file without explicitly knowing its length, and how do you use that data afterwards?Q: How do you compile the happy face on matrix? What is correct way to use CIO library in matrix?
</pre>
'''Q:''' Why is the postfix increment/decrement operator (e.g. a++ and a--) evaluated differently on different compilers?<br>
'''Q:''' How to visualize a multi-dimensional array? <br>
'''A:'''  The simplest way to do so for a 2 dimensional array is a table
<source lang="cpp">
0123
Submitted by Team42
<br><br>
'''Q:''' What is the correct way to pass a 2D array (called array) into a function? Which of the following is right: array[][], array[][COLS] or **array?
<br>
'''A:''' Any of the stated syntaxes are acceptable for passing a 2D array into a function. Generally the 2nd syntax (array[][COLS]) is used if the array is static and the number of cols is known. This is in order to reveal the preferred structure to the compiler, since the compiler stores a 2D array as one really long array with arrays as its elements. For example an array[3][3] would looks something like this in memory '''|''' |||| '''|''' |||| '''|''' |||| '''|''' where as we perceive the structure as a table. The other 2 syntaxes are equivalent and are generally used to pass a 2D array into a function if the structure is not know, hence for dynamic created arrays.
*Comment (pliu): Excellent question and explanation. We need to make a distinction between a STATIC 2-d array and a 2-d array that is created by DYNAMAC MEMORY ALLOCATION.<br>
'''Submitted by:''' Team 6 <br><br>
----
<br><br>
'''Q:''' When creating the header file for a template class and putting the implementation in the header as well there are no errors. However when splitting the deceleration (header) and implementation (making a cpp file) for that class template there are numerous compile errors. What do all these errors mean?
 
Possible errors:
 
arrayWrong.cpp:6:1: error: invalid use of template-name 'Array' without an argument list
 
arrayWrong.cpp:12:1: error: invalid use of template-name 'Array' without an argument list
 
arrayWrong.cpp:24:1: error: invalid use of template-name 'Array' without an argument list
 
arrayWrong.cpp:30:1: error: invalid use of template-name 'Array' without an argument list
 
arrayWrong.cpp:46:14: error: 'template<class T> class Array' used without template parameters
 
 
<br>
*comment (pliu): Could you please post up the source code and the listing of compiler error messages please? <br>
'''A:''' When splitting the deceleration of a template class additional code must be added onto every method of that class. If one has a class called Stack and a function called add(int x) for example, then in the implementation file the display function would be defined in the scope of the Stack class by writing int Stack::add(int x). Since templates are being used the compiler must also be told that this implementation is being defined with a template. This is done by writing something like template<class T> before every function. For the example stated it would look like this:
 
template<class T>
 
int Stack<T>::add(T x)
<br>'''Submitted by:''' Team 6 <br><br>
----
<br><br>
'''Q:''' Can Stacks, Queues or Lists be referenced using indexes?
<br>
'''A:''' The answer is no. Linear data structures are used when the programmer does not know how many elements of an array there are going to be overall(assuming arrays are used over linear data structures)by the end of the programs termination. The problem that arises with using arrays when the number of elements is unknown is that dynamic allocation, copying and deletion need to be preformed every time a new element is added, altered or deleted in a sequence of data. In order to keep an index of the Nodes (in a linear data structure) a dynamic array would have to be made with a number to signify the artificial index of the linear data structure Node. The programmer could then refer to an index of the array that will automatically loop through the linear data structure (via a code block) to give a result. This would defeat the purpose of a linear data structure because the array holding the indexes would have to be deleted and reallocated every time the linear data structure changes.
 
Example explanation: A stack has numbers 15 10 5 on it and an array allocated to 3 indexes (with values 0, 1, 2) to match the number of Nodes. If a person adds 1 more data to the Stack (push(20))then the array would have to be deleted and reallocated, defeating the purpose of the stack in the first place.
<br>'''Submitted by:''' Team 6 <br><br>
'''Q:''' How to get size of an array without storing the size anywhere? <br>
'''A:''' There are several ways to get the length of an array without explicitly knowing its length. The C method is as follows
<source lang="cpp">
#define SIZEOF_ARRAY( a ) (sizeof( a ) / sizeof( a[ 0 ] ))
</source>
The above define macro can be called to find the size of an array in a C manner. This function exists in the std namespace.<br>
One could also use the below code for a more effective (but c++ only) solution.
<source lang="cpp">
#include <iostream> using namespace std;
template <typename T, size_t N>
 
inline
 
size_t SizeOfArray( const T(&)[ N ] ) {
 
return N;
 
}
 
 
int main() {
 
const char s[] = "Hello world!";
cout << "s[] is " << SizeOfArray( s );
}
</source>
The good thing about the above method is not only its improved efficiency (most compilers will optimize the template function out of existance upon compilation) but the fact that it will not work with a pointer to an array, such as
<source lang="cpp">
const char* s = "Hello world!"; cout << "s is " << SizeOfArray( s )
</source>
Lastly, with C++11 there is an even better method of doing this: std::extent. More info on this trait class can be found [http://www.cplusplus.com/reference/std/type_traits/extent/ here].<br>Submitted by Team42.<br><br>
 
'''Q:''' How do you get the length of a file / read the entire file without explicitly knowing its length, and how do you use that data afterwards? <br>
 
'''A:''' There are several ways to read the contents of a file without knowing it's length and then split the result into usable parts.
First, you could use a string class and load the contents of the entire file into the string object. At this point you can manipulate it as any other string object (not to be confused with a char array) by using methods such as find, substr, erase, etc as outlined [http://www.cplusplus.com/reference/string/string/ here]
<source lang="cpp">
std::ifstream in("myfile", ios::binary);
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());
</source>
You could also use
<source lang="cpp">
inMyStream.seekg(0,std::ios_base::end);
std::ios_base::streampos end_pos = inMyStream.tellg();
return end_pos;
</source>
to get the length of the file without actually reading it, and then if needed read / append / modify it as required using a char array.. This method of getting a file's length can be used with char arrays / strings / vectors without problems.
Lastly, you could also load the file into a vector and manipulate it as a vector object from that point onwards (more advanced topic) like so
<source lang="cpp">
std::ifstream ifs("foobar.txt", ios::binary);
ifs.seekg(0, std::ios::end);
std::ifstream::pos_type filesize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::vector<char> bytes(filesize);
ifs.read(&bytes[0], filesize);
</source>
For any of these methods, to be able to work with the data afterwords simply use a common delimiter when originally generating the file, and then you can use methods like [http://www.cplusplus.com/reference/clibrary/cstring/strtok/ strtok] (for char array), [http://www.cplusplus.com/reference/string/string/find/ .find] combined with [http://www.cplusplus.com/reference/string/string/substr/ .substr] (string class) or use it as a vector (if that's required).<br>Submitted by Team42.<br><br>
 
Q: How do you compile the happy face on matrix? What is correct way to use CIO library in matrix?
Details of problem/question: The CIO library files (console.h, console.cpp, keys.h) and Happyface.cpp were transferred to Documents\A_1 folder on zenit. And when attempt was made to compile happyface.cpp, the lots of errors were generated that stated
"undefined reference to 'cio::console' or
"undefined reference to 'cio::console::(some function)'.
You can find the happyface.cpp at https://scs.senecac.on.ca/~btp300/pages/content/names.html (just scroll to the bottom)
This just happens only on zenit. The program works ok on visual studio. [Asked by Soban Akbar]
 
A: In order to compile the happyface.cpp on linux, you have to use "g++ console.cpp happyface.cpp -lncurses". [Answered by Soban Akbar]