Good evening,

There is a code:

int *[] a;//массив указатилей int kol = 5; a = new int*[kol]; int[] some = new int[kol]; //тут мы заполняем левыми данными some, пускай это будут числа 1, 2, 3, 4, 5 

then I want to take and in each a [i] put a pointer to some [i]

 for(int i=0;i<kol;i++) a[i] = &(some[i]); 

tried the same

 for(int i=0;i<kol;i++) a[i] = some+i;//как бы some возвращает указатель на 0 эл. 

so how can we do that in our array of pointers we can transfer pointers to elements of the array some? ZY The task is to have a class, and in it there is an array of pointers to ints. therefore, the fixed construction does not know how to insert here.

  • a[i] = &some[i]; - so does not work? - Denis Bubnov
  • And where does C #? Your code is clean C. - VladD
  • @DenisBubnov: Oh God! Is it really unsafe code? o_O - VladD
  • @VladD, I never would have thought that someone like this in C # ... but I saw it. Somehow, for the sake of interest, even tried this. Strange, but the author is not responding to comments ... - Denis Bubnov

1 answer 1

fixed syntax is similar to using , it is only intended to pin (pin) an object on the heap and get a pointer to this object. Docking is necessary because the object can be moved by the garbage collector and the pointer obtained earlier will not be valid. After exiting the fixed block, the object becomes available to the collector again.

Example:

 int kol = 5; int*[] a = new int*[kol]; int[] some = new int[kol]; fixed (int *p = some) { for (int i = 0; i < kol; ++i) { some[i] = i + 1; // Элементы массива располагаются в памяти непрерывно // Как и в С, sizeof(int) при сложении учитывается a[i] = p + i; Console.WriteLine("Address: 0x{0}, Value: {1}", new IntPtr(a[i]).ToString("X"), *a[i]); } } 

Result:

 Address: 0xFF1E0D99C8, Value: 1 Address: 0xFF1E0D99CC, Value: 2 Address: 0xFF1E0D99D0, Value: 3 Address: 0xFF1E0D99D4, Value: 4 Address: 0xFF1E0D99D8, Value: 5 

You mentioned that you want to create a class in which there will be a field with an array of pointers. Here you need to be careful, because you have to keep some array fixed for at least as long as the array of pointers to it will be used (which is more likely - as long as an instance of the class exists, especially if some passed to it from somewhere outside) . If it is difficult to do this through fixed , then use GCHandle.Alloc with type GCHandleType.Pinned .