I have some C code I am trying to translate into C# code and I'm running into pointers which I am not familiar with so I don't know the C# equivalent. Get I get some help?
Case 1: Given these three lines in C, how do I declare p in C#?
double snorm[169];
double *p = snorm;
*p = 1.0;
Case 2: I have no idea what the pointers are actualy doing so I don't know how to change this line to C#.
*(snorm+n) = *(snorm+n-1) * (double)(2*n-1) / (double)n;
First:
double[] snorm = new double[169];
snorm[0] = 1.0;
Than just use snorm instead of p.
Second:
snorm[n] = snorm[n-1] * (double)(2*n-1)/(double)n;
Basically *p means that you take the value at the address of memory, referenced by p. Incrementing and adding to the pointer are moving the pointer in memory, so p++, as well as (p+1) just refers to the next item in memory (how far it really moves in memory depends on the data type the pointer points to). And, *(p+n) is just a value of the n-th item in the array (if p points to an array)
Anyway, you should get yourself familiar with pointers.
That code is basically using pointers as an alternative to array access. So your first snippet is equivalent to:
double[] snorm = new double[169];
snorm[0] = 1.0;
The next bit is equivalent to:
snorm[n] = snorm[n-1] * (double)(2*n-1) / (double)n;
(I'd use more spaces, but obviously that's a matter of taste.)
The only tricky bit is going to be if something increments a pointer - at that point you'll need to remember that you've basically got an extra offset to add to any future array indexes.
Related
This thread in SO is about multidimensional array in c++.
I have to port some code from c# to cpp. i have code like this:
private double[,] B;
...
this.B = new double[states, symbols];
double[][, ,] epsilon = new double[N][, ,];
double[][,] gamma = new double[N][,];
...
s += gamma[i][t, k] = ...
i have thought to use plain double array of array but it's quite pain. another solution could be vector of vector of double, or a custom Matrix2D and Matrix3D classes?
what is the best way for each of those cases?
WHAT I LEARNED:
multidimensional array in c++ is a great topic, and internet is full of resources. it could be handled in various ways, some of them really tricky, some others more faster to write.
i think that the best way is to deal with it is to use some libraries that takes in account this topic. there are a lot of them: Armadillo (nice MATLAB syntax conversion), Eigen i think is one of the better one, easy to install, easy to use, powerfull. Boost::multi_array is anotherone, and Boost is really a famous lib that is important just to take a look at how it handle the topic. As Konrad Rudolph answer STD with nested vectors or this could be another solution but, after a little search, i think the less elegant even the more easy and fast to code without external libs.
write a custom class. mayebe such a good exercice. peter answer or this or this are a good start point and also this post is interesting but expecially this great post blog from martin moene (one of the best essay on this topic i've read today). I mention also this answer for sparse array.
here is a nice tutorial direct from stroustrup
have a nice time with multidimensional array :-)
C++ has no direct equivalent of T[,] (although you could of course implement one by encapsulating the following code in a class. This is left as an exercise to the reader.
All C++ supports is nesting arrays/vectors (the equivalent of [][] in C#). So your first code would correspond to
vector<vector<double> > B(states, vector<double>(symbols));
… which initialises a vector of vectors, initialising the outer vector with states copies of an appropriately initialised inner vector.
Of course this can be taken to arbitrary complexity but at this point a few typedefs are in order to make the code more understandable.
class StateSymbols
{
public:
StateSymbols(unsigned int states, unsigned int symbols) :
m_states(states),
m_stateSymbols(states * symbols)
{
}
double get(unsigned int state, unsigned int symbol) const
{
return m_stateSymbols[(m_states * symbol) + state];
}
private:
const unsigned int m_states;
std::vector<double> m_stateSymbols;
};
Check out my answer on:
C++ Multi-dimensional Arrays on the Heap
It defines a basic function Create3D to allocate a 3D (generalizes to other dimensions) array in contiguous memory on the heap in a way that allows A[i][j][k] access operator syntax.
I would say dynamic array:
double* *list;
list = new double*[3]; //dimension1=3=row
for(int i=0;i<3;i++)
list[i] = new double[2]; //dimension2 =2 =col
list[0][0] = 1;
//...
for(int i=0;i<3;i++)
delete [] list[i];
delete [] list;
I'm trying to create an array of pointer references to a double array. For example;
double[] mylist = new double[100];
fixed (double* p = mylist) { }
Now as the MSDN documentation states, that is equivalent to p = &mylist[0] This is only taking the first value, is it possible to create an array of pointers to variables in another array? Or is the practice to use only one pointer?
Thanks for any help, in advance
Array elements are located in contiguous memory, so it's usually suffcient to have a pointer to the first element and do pointer arithmetic to get to the others.
When you have a typed pointer to a vector (or, more accurately, the first item in a vector), it works like in C/C++; all you need is the single pointer, and you can use it either as an individual item or as a zero-based array; you can still access p[3], except now instead of using array access metaphors, this is applying "3 * the-item-size as an offset relative to p". So:
p[3] = 1.0;
is fine. Note, of course, that if you go outside the array bounds accidentally, bad things will happen.
Ok, so In one of my projects, im trying to remake the way it stores certain variables, i have a simple array of objects. The class that these objects refer to is:
class Blocks
{
public byte type = Block.Empty;
byte lastblock = Block.Zero;
}
I plan to add more to it, in the current class type is what the objects current value is, and lastblock is what the object used to be.
i create the array like this:
blocks = new Blocks[width * depth * length];
for (int i = 0; i < ((width * length) * depth); i++)
{
blocks[i] = new Blocks();
}
The problem that I'm having, is that when i create an array that's very large (512,512,512 or 134217728 for those of you whom don't like math), the array gets huge, upwards of 3.5 gigs.
The old way that this array was created was a little simpler, but much harder to expand, it simple created an array of bytes representing the current block, and seems to only use 2 megs of ram when its actually loaded (which i dont get since 134217728 bytes should be around 134 megs... right?). It just baffles me that object references could generate that much more ram usage.
Am i doing something wrong, or should i just go back to the old way it was done? I would like the object references simply because it means that all my variables are in 1 array rather then in 4 separate arrays, which seems as though it would be better for the system.
EDIT:
After working through a few different ways of doing this, i found that changing
class Blocks
to
struct Blocks
Made a world of difference, Thank you community for that welcome tip for future use, unfortunately i didn't want to just add two bytes in a struct and call it done, that was where i stopped to test my design and wound up with the original problem. After adding anything else to the struct (anything else that's on my list at least, meaning either a player object reference or a player name string.) It causes an out-of-memory exception that means I'm not going to be able to use this system after all.
But the knowledge of how to do it will be quite helpful in the future. For that, thank you again.
Here's what I tried with a structure type instead of a class type:
public struct Block
{
public byte _current;
public byte _last;
}
public static void RunSnippet()
{
Block[] blocks = new Block[512 * 512 * 512];
for (int i = 0; i < ((512 * 512) * 512); i++)
{
blocks[i] = new Block();
}
}
The snippet ran almost instantly and ate around 267 Mb of RAM.
So give struct a try if that's possible.
You can use List class to manage unlimited number of objects. Please take a look at the link that I provided. You can add infinite (well, theoretically) number of objects into a list.
Using lists, you can easily access any item by their index. It also has methods to search, sort and manipulate objects contained in it.
If you use list, your code will look somewhat like below -
List<Blocks> blocks = new List<Blocks>();
for (int i = 0; i < ((width * length) * depth); i++) // The amount of items that you want to add
{
Blocks b = new Blocks();
blocks.Add(b);
}
You can access every item in this list as follows -
foreach(Blocks b in blocks)
{
// You have the object, do whatever you want
}
You can find any particular index of an object contained in the list. See this method example.
So using a list, you will be able to easily manage a large number of objects in an uniform way.
To learn more, go here.
You should consider using "struct" instead of "class".
http://msdn.microsoft.com/en-us/library/ah19swz4(v=vs.71).aspx
"The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive."
Please publish your results if you try so.
When you create the array, you also instantiate a Blocks on each cell. Do you really need to do that?
blocks[i] = new Blocks();
When you don't instantiate a Blocks, you'd just have an array of empty references. In the access code you could check for null and return a default value. Something along these lines:
if(blocks[i,j] == null) return new Blocks();
else return blocks[i,j];
When writing also check if there is one, if not, create it first. That should save a lot of memory.
Using jagged arrays or nested lists should also help a lot.
Regards GJ
Structs are the way forward here, and would open up the possibility of optimising with unsafe code/pointer arithmetic
struct Block
{
byte Current;
byte Last;
}
Block[] blocks = new Block[512 * 512 * 512];
unsafe
{
Block* currentBlock = &blocks;
for (int i = 0; i < (512 * 512) * 512; i++)
{
currentBlock->Current = 0xff;
currentBlock->Last = 0x00;
currentBlock++;
}
}
Of course someone will come along and say mutable structs are evil! (Only if you dont know how to use them)
Read this: Object Overhead: The Hidden .NET Memory Allocation Cost.
The total cost of an object of yours is like 16 bytes (on a 32 bits system). (8 bytes for "header", 4 bytes for your fields, 4 for the reference) And 512 * 512 * 512 * 16 = 2.1gb :-)
But you are probably on a 64 bits system, so it's 16 + 8 + 8 = 28, so 4.29gb.
It's easier to write
intArray1.CopyTo( intArray2, 0 )
than the for-loop equivalent, but System.Array does not provide any generic Copy/CopyTo methods.
Is it better to write the for-loop? Or is using Copy/CopyTo compiled or JIT'd efficiently enough?
Array.Copy/CopyTo will perform faster than a manual loop in most cases as it can do direct memory copying.
If you don't have huge arrays or speed is not an issue, use whatever would look best in your code where you need to copy the items.
If you are copying an array of primitive types as your sample would imply, you can us the memory copy technique yourself using the Buffer classes BlockCopy method.
int[] CopyArray(int[] A, int index)
{
const int INT_SIZE = 4;
int length = A.Length - index;
int[] B = new int[A.Length - index];
Buffer.BlockCopy(A, index * INT_SIZE, B,
0 * INT_SIZE, length * INT_SIZE);
return B;
}
This method is the most efficient manner in which to copy an array of primitives. (It only works with primitives)
I say if you know that you want to copy the entirety of the first array to the second array without changing the values or doing any specific processing on the copy, then use Array.CopyTo.
There are some limitations to this. The array must only have a single dimension as I remember it. Also if the arrays are quite large you might have some speed related issues with the copyto, but I would imagine that would only come into play with very large arrays. So, I would try it and test it, but your mileage may vary.
I spend much of my time programming in R or MATLAB. These languages are typically used for manipulating arrays and matrices, and consequently, they have vectorised operators for addition, equality, etc.
For example, in MATLAB, adding two arrays
[1.2 3.4 5.6] + [9.87 6.54 3.21]
returns an array of the same size
ans =
11.07 9.94 8.81
Switching over to C#, we need a loop, and it feels like a lot of code.
double[] a = { 1.2, 3.4, 5.6 };
double[] b = { 9.87, 6.54, 3.21 };
double[] sum = new double[a.Length];
for (int i = 0; i < a.Length; ++i)
{
sum[i] = a[i] + b[i];
}
How should I implement vectorised operators using C#? These should preferably work for all numeric array types (and bool[]). Working for multidimensional arrays is a bonus.
The first idea I had was to overload the operators for System.Double[], etc. directly. This has a number of problems though. Firstly, it could cause confusion and maintainability issues if built-in classes do not bahave as expected. Secondly, I'm not sure if it is even possible to change the behaviour of these built-in classes.
So my next idea was to derive a class from each numerical type and overload the operators there. This creates the hassle of converting from double[] to MyDoubleArray and back, which reduces the benefit of me doing less typing.
Also, I don't really want to have to repeat a load of almost identical functionality for every numeric type. This lead to my next idea of a generic operator class. In fact, someone else had also had this idea: there's a generic operator class in Jon Skeet's MiscUtil library.
This gives you a method-like prefix syntax for operations, e.g.
double sum = Operator<double>.Add(3.5, -2.44); // 1.06
The trouble is, since the array types don't support addition, you can't just do something like
double[] sum = Operator<double[]>.Add(a, b); // Throws InvalidOperationException
I've run out of ideas. Can you think of anything that will work?
Create a Vector class (actually I'd make it a struct) and overload the arithmentic operators for that class... This has probably been done already if you do a google search, there are numerous hits... Here's one that looks promising Vector class...
To handle vectors of arbitrary dimension, I'd:
design the internal array which would persist the individual floats for each of the
vectors dimension values an array list of arbitrary size,
make the Vector constructor take the dimension as an constructor parameter,
In the arithmentic operator overloads, add a validation that the two vectors being added, or subtracted have the same dimension.
You should probably create a Vector class that internally wraps an array and overloads the arithmetic operators. There's a decent matrix/vector code library here.
But if you really need to operate on naked arrays for some reason, you can use LINQ:
var a1 = new double[] { 0, 1, 2, 3 };
var a2 = new double[] { 10, 20, 30, 40 };
var sum = a1.Zip( a2, (x,y) => Operator<double>.Add( x, y ) ).ToArray();
Take a look at CSML. It's a fairly complete matrix library for c#. I've used it for a few things and it works well.
The XNA Framework has the classes you may be able to use. You can use it in your application like any other part of .NET. Just grab the XNA redistributable and code away.
BTW, you don't need to do anything special (like getting the game studio or joining the creator's club) to use it in your application.