C++ Question Misc. C++ questions

N_Molson

Addon Developer
Addon Developer
Donator
Joined
Mar 5, 2010
Messages
10,002
Reaction score
4,418
Points
203
Location
Toulouse
A thread for C++ questions that are not related.

Here's a first one. I'd like to have index [ j ] = index [ i ] + 2. But it looks like my way of expressing it is too unorthodox :

1765731458330.png

Edit : obviously there was an error here : it should have been GetThrusterLevel and not GetThrusterGroupLevel...
 
Last edited:
So, let's say I want to print something on my HUD, and use 'char' variables for that. What is the correct syntax in this case ?

1765821338386.png

1765821391348.png

I get I should 'allocate' a number of characters (in this example, 6). But where ?
 
A char can only store a single byte, you need an array to store a string and a pointer to use it.
Using a double quoted string does the job.
Also in your sprintf, the string format needs to specify that you're going to give it a string :
C++:
const char *RCSmode = "Coarse";
sprintf(abuf, "RCSMode: %s", RCSmode);
You need to make sure that abuf is large enough to contain the resulting string or you'll end up with a crash (including the final NUL terminating char used by C strings).
Since you're using C++ there is also the lazy way :
Code:
std::string RCSmode = "Coarse";
std::string abuf = std::string("RCSMode: ") + RCSmode;
skp->Text(..., abuf.c_str(), abuf.length());
 
Just a little insight into arrays in C/C++:
An arrray is in essence just "syntactic sugar" for pointer-arithmatic.
If you have for example defined an array of 4 integers,
C++:
int a[4] = { 42, 43, 44, 45 };
the symbol 'a' is internally just a pointer to the first element.
Using the index-operator ([]) just adds the index to the pointer. This is also the reasoning why C/C++ starts countig from 0, as it's much more efficient this way.
So defining this...
C++:
int a[4] = { 42, 43, 44, 45 };
int i = 1;
... and accessing the 2nd Element (Index 1, you know) by...
C++:
a[1]
... is just the same as...
C++:
&a + 1
(the ampersand is just here to emphazise that 'a' is actually a pointer to int)
Incrementing a pointer-to-a-type by an integer 'N' just increments the pointer value by 'N' times the size of the type.

With this knowledge you can see why this COMPLETELY INSANE programming is still working:
C++:
#include <iostream>
int main (int argc, char** argv)
{
  int a[4] = {42,43,44,45};
  int i = 1;

  int x = a[i];
  int y = i[a]; // WHAAAAT?! But it's the same as above!

  std::cout << "x:" << x << ", y:" << y;

  return 0;
}
The above does print out the (un)expected result:
Code:
x:43, y:43

..just to keep the confusion level up :LOL:
 
Last edited:
Back
Top