this cold be really obvious but I havent done C++ in about 15 years so thanks in advance.
I have a 2D array of strings and when I read from it I get this:
0x22fc90
Here is my code, any ideas?
std::string results[3][3] = {
{"Draw", "Win", "Lose"} , /* initializers for row indexed by 0 */
{"Lose", "Draw", "Win"} , /* initializers for row indexed by 1 */
{"Win", "Lose", "Draw"} /* initializers for row indexed by 2 */
};
cout << "It's a " << results[choice,compChoice];
choice and compChoice are integers
There is a difference between for example the C++ syntax and the C# syntax for multidimensional arrays. What you wrote in this statement relative to accessing an element of the array
cout << "It's a " << results[choice,compChoice];
is valid in C# and does what you mean.
In C++ this statement
cout << "It's a " << results[choice,compChoice];
is also valid but its meaning is different. There is used the so-called comma operator in the subscript operator results[choice,compChoice] that in fact is equivalent to results[compChoice] except that the first subexpression will not be evaluated. So results[compChoice] gives a row of the two-dimensional array and operator<< outputs its address.
What you want is the following
cout << "It's a " << results[choice][compChoice];
Access the array using results[choice][compChoice].
That's because two dimensional arrays are actually arrays of arrays.
First you need to go into results[choice] and then you select [compChoice] from that.
choice,compChoice just evaluates to compChoice, so you are just outputting the pointer to the start of the choiceth array in results. Use results[choice][compChoice] instead.
results is an array of arrays. Try accessing via
results[choice][compChoice]
So results[choice] "returns" an array that you can access with another [] operator. As far as I know, multiple indices aren't supported in one pair of brackets.
Thanks everyone.Am glad it was a syntax issue am not me missing the point completely!
Related
This is a multi part question based on a project I'm currently undertaking. I will try to make it as brief as possible while still fully explaining the question, so sorry if this is a bit long.
When it comes to std::vectors in C++, how exactly do they work with variables? For example, if I have the following code:
int myInt = 4;
std::vector<int> myIntVector;
myIntVector.push_back(myInt);
what happens? Does that area of memory inside myIntVector now have the same value of data stored inside myInt at the time of adding, but still completely separate them? Does the area of memory where myInt is stored get physically moved into a designated area inside of the memory of myIntVector?
Assuming I was correct on the last statement, why would std::cout << myInt still correctly print 4, assuming it was not changed, while std::cout << myIntVector[0] also prints out 4?
Now, for what prompted the question: the #define directive. I was experimenting with this for my project, and noticed something interesting. I used #define GET_NAME(variable) (#variable), which returns the name of the inputted variable as a character array. If I were to have the following code:
#define GET_NAME(variable) (#variable)
int myInt = 4;
std::vector<int> myIntVector;
myIntVector.push_back(myInt);
std::cout << GET_NAME(myInt) << "\n";
std::cout << GET_NAME(myIntVector[0]);
I would receive the following output:
myInt
myIntVector[0]
Why? Assuming the first statement from question 1 is correct, this is the expected output, but then we circle back to question 2. Assuming the second statement from question 2 is correct, this is the unintended output, as myInt or myIntVector[0] should be returned twice.
Thanks in advance!
When it comes to std::vectors in C++, how exactly do they work with variables?
All STL containers just copy values by default. So when you pass an int variable, it gets copied and the copy exist completely independently from the original value
why would std::cout << myInt still correctly print 4, assuming it was not changed, while std::cout << myIntVector[0] also prints out 4?
These are two different values, both equal to 4
If I were to have the following code, I would receive the following output. Why?
The macros just manipulate the text, and don't do anything fancy in your code. This statement:
std::cout << GET_NAME(myInt) << "\n";
Just turns into this under the macro:
std::cout << "myInt" << "\n";
I recently stumbled upon following code
int array[] = {10, 20, 30};
cout << -2[array];
I understand that array is a pointer to the first element of the array but then what does [pointer] means and then we write -2 in front of it which looks very alien to me.
It is the same as if you'd write
cout << -(2[array]);
which is the same as
cout << -(array[2]);
In C++ operator [] on an array simply offsets the address of the array by the number specified in the brackets. As with any addition, you can swap operands and the result will remain the same.
For example -0[array] will give you -10 in this case.
There are two ways to access an array element via a pointer offset. One is the common
int array[] = {10, 20, 30};
cout << -array[2]; // prints -30
and one is the unusual one that you posted. Both versions are equivalent.
Note that as the unary minus operator has a lower precedence compared to the subscript operator, -2[array] does not involve a negative index, but instead is the same as -(2[array]).
In C and C++ the place of array name and the index can be swapped without changing the meaning i.e. -2[array] and -array[2] are the same. Both will compile and do the same thing. Check this SO post
However, if you try this in a language like C# or Java you will get a compiler error saying Cannot apply indexing with [] to an expression of type 'int' or something similar. This is a good example to understand how code works if the language supports pointers vs if it doesn't.
Note, as pointed out in the comment, negation operator has lower precedence over array index operator so it will compute to -array[2] instead of array[-2]
Hello all c++ noob here,
For my homework in c++ I must create a program that inputs 5 cities and prints them in order and reverse order by the users choice using arrays and seperate functions. The homework requires that you use all these functions to operate. The program runs fine until I enter o or r for reverse order. I get a segmentation error. I think I am printing or passing the strings incorrectly.
Here is my declaration of my array function
void displayInOrder (string o[5]);
Now here is my function with the executable code.
void displayInOrder (string o[5])
{
cout << "Here are the cities in order: " << endl;
cout << o[0] << " " << o[1] << " " << o[2] << " " << o[3] << " " << o[4]
<< endl; //the error seems to lie somewhere in here and the same
//in the reverse function
}
Now in the main I am calling the function like this.
displayInOrder (&cities[5]);
I think I am either calling the function incorrectly, declaring it wrong, or printing it wrong. It's been a while since I programmed in C++ and I am a bit of a noob. I appreciate any help anyone has to offer.
The displayInOrder() function is expecting a pointer to an the whole array. Instead, you passed a pointer to cities[5]. This has two problems:
It's a pointer to a specific element, not the whole array.
The last element of the array is cities[4], so you're accessing outside the array bounds.
You should call the function this way:
displayInOrder(cities);
There's no need to use &, an array variable automatically decays to a pointer when used as a function argument.
Is there a way to declare 2 dimensional static array which is compatible with the dynamic pointer (TYPE**) ?
char strs1[2][256] = { "String 1", "String 2" }; // Static
What I want is to assign it to
char **strs2 = strs1;
Well, I can do something like that:
std::array<std::array<char, 256>, 2> arr = {"String 1", "String 2"};
char *temp[2] = { (char*)&arr[0], (char*) &arr[1] };
char **strs = (char**)temp;
cout << strs[0] << endl;
cout << strs[1] << endl;
// Output
String 1
String 2
But is there a better and simpler way to achieve the same result ?
char** can never be a way to reference a an array of arrays (there are no two-dimensional arrays in C/C++) because it doesn't have the information on the inner array size. In particular, there is no way compiler can generate a proper access code in following snippet:
char** arr = initialize_by_hack();
arr[2][4] = '42';
Here, to calculate second offset (4) compiler needs to know the size of element array - but is is nowhere in the code and not available.
No, you cannot change the fact that a two-dimensional array is incompatible with a T**.
You can only perform hacky workarounds like the one you posit in your question, or remedy the mistake or design flaw that initially led you to the requirement.
Since you're writing C++: why not use proper, modern, type-safe technologies rather than native arrays and a mess of pointers? A simple Matrix<T,W,H> class template that wraps a statically allocated T[W*H] but exposes two-dimensional indexing would be nice. Then just pass it around by reference (or, if you really must, by pointer).
I am trying to overload the operator[], however, something funky is going on.
To avoid long codes here, I put the code on GitHub (I'll keep the code as is there forever).
The issue is that when I access the subscript, it doesn't return the GameEntry when accessing s[0], but Scores. In addition to that the << operator returns the whole array, while I was requesting only one of the entries.
Please, advise. Thanks
EDIT: The operator[] is declared on line 58.
This line declares pointer to Scores:
Scores *s = new Scores(5);
So instead of
cout << typeid(s[0]).name() << endl;
try
cout << typeid((*s)[0]).name() << endl;