简体   繁体   中英

How to create a dynamic array of int pointers in c#?

I want something like std::vector<int*> v from C++, but in C#.

I tried List<int*> v , but the compiler said that

CS0306 C# The type may not be used as a type argument

I want to put int variables and change it through the array something like that in C++

std::vector<int*> v;
int a = 2;
v.push_back(&a);
v[0] = 4; // (a == 4) true

First off let me say very clearly: solving problems in C# using the same low-level pointer techniques as you would in C++ is almost always the wrong thing to do . There is usually a higher-level, safer technique you can use. What you're doing here is called an "XY question" -- you have a wrong idea about how to solve a problem, and you're asking a question about the wrong idea, instead of asking how to solve the real problem; please edit the question to say what the real problem is.

To answer your question that was asked: to make a "dynamic array" of pointers in C# you must make a List<IntPtr> which is a list of "integers that are the same size as a pointer". Do not fall into the trap of believing that IntPtr means pointer to integer . An IntPtr is an integer that is the same size as a pointer .

You can then convert your int* s to IntPtr and store them in the list, and then convert them back again when you're done, but again, this is almost always the wrong thing to do , and if you do so then you are responsible for understanding everything about the .NET memory management system and how it works, because you are turning off the safety system that protects memory integrity .

Do you believe that you understand everything about how memory management works in C#? If not, then do not use pointer types in C# . I have been developing code in C# since 2001 and I have never used pointer types for anything in production code. You don't need them, and if you think you need them, you're probably doing something wrong.

You can solve the lack of having a pointer to a value type by creating a wrapper to the value like that:

static void Test()
{
  var v = new List<EmbeddedInt>();
  var a = new EmbeddedInt(2);
  v.Add(a);
  v[0].Value = 4;
  Console.WriteLine(a);  // Display 4
}

public class EmbeddedInt
{
  public int Value { get; set; }
  public override string ToString()
  {
    return Value.ToString();
  }
  public EmbeddedInt(int value)
  {
    Value = value;
  }
}

This is a simple example here.

To be able to compute on the value without using a + 2 instead of a.Value + 2 you may implement some methods like operators.

The only thing you can't do is overloading the assignment operator...

Take a look at this:

Define assigment operator that change the value of some "this" in C#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM