C# Array Pointer

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 13180 Views - Last Post: 08 May 2011 - 06:19 AM Rate Topic: -----

#1 kenryuakuma  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 381
  • Joined: 14-December 08

C# Array Pointer

Posted 05 May 2011 - 07:06 PM

using System; 
 
public class PtrIndexDemo { 
 unsafe public static void Main() { 
  int[] nums = new int[10]; 
 
  // index pointer 
  Console.WriteLine("Index pointer like array."); 
  fixed (int* p = nums) { 
   for(int i=0; i < 10; i++) 
    p[i] = i; // index pointer like array 
 
   for(int i=0; i < 10; i++) 
    Console.WriteLine("p[{0}]: {1} ", i, p[i]); 
  } 
 
  // use pointer arithmetic 
  Console.WriteLine("\nUse pointer arithmetic."); 
  fixed (int* p = nums) { 
   for(int i=0; i < 10; i++) 
    *(p+i) = i; // use pointer arithmetic 
 
   for(int i=0; i < 10; i++) 
    Console.WriteLine("*(p+{0}): {1} ", i, *(p+i)); 
  } 
 } 




Just wonder how the code works?

As far as I know, the code below, p receives the address of the first element of the nums array. But how can p be indexed? Does it change the address of p?...What does it do and how it work? I am pretty sure that it doesn't work the same as array indexing. And what is this btw *(p+i)? Really some detail explanation.

Is This A Good Question/Topic? 0
  • +

Replies To: C# Array Pointer

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 05 May 2011 - 07:26 PM

Out of curiosity...

You didn't write this code or you wouldn't need an explanation.
So where did it come from?
Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 05 May 2011 - 07:41 PM

Attached Image

Lines 9 gets the address of the array and assigns it to P. No magic there.

Lines 10-15
Just a loop assigning values to the elements of the array in a typical manner and having nothing to do with the pointer. Nothing mysterious there.

Lines 19-25 go through a loop, get the starting address of the array, then increment by one with each iteration of the loop, getting the value at that memory address.

It might be easiest to understand if you put a breakpoint as shown and walk through it line by line, seeing the change in address with each iteration.

Notice the values as shown below during the 7th iteration of the loop. You can see the index counter as well as the address of the array element. Then it's just a matter of getting the value at that address.

Attached Image
Was This Post Helpful? 0
  • +
  • -

#4 kenryuakuma  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 381
  • Joined: 14-December 08

Re: C# Array Pointer

Posted 05 May 2011 - 08:29 PM

The code was extracted from the reference book...I came across with this and don't really understand how the code work, so ask questions here. Dreamincode is a place for students to learn and lots of pros here are to help newbies.

//to get the address of the variable, we do something like this
int* p = &nums[0]

//which is equivalent to 
int *p = nums

//However, to assign value or extract a value from the variable where the pointer points to,
//we will do something like this
int v = *p;

//The statement above will get the value from nums[0] and same with assigning values
*p = 100;



However the problem is that since fixed (int* p = nums)
this is only getting the address of nums[0]. But when assigning values, the author did something like this p[i] = i; through the loop.

Aren't we supposed to assigning values to the pointer like this *p = i;?
Besides, when we wanna reference or point to another address, aren't we supposed to assign the pointer variable to another address by doing something like this *p = &nums[1] if we wanna reassign the pointer variable to another address and in this case nums[1]?

Besides what does this mean *(p+i) = i;? I just don't get it and this has really confused me.
Was This Post Helpful? 0
  • +
  • -

#5 marinus  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 135
  • View blog
  • Posts: 575
  • Joined: 14-April 10

Re: C# Array Pointer

Posted 06 May 2011 - 12:34 AM

int p = an pointer to an array..

Now this means that int p is an pointer to an array,

all he is showing you with this code
*(p+i) = i;


is that a pointer to that index of p array = i;

So he is just filling int p with the value of i

This post has been edited by marinus: 06 May 2011 - 12:48 AM

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 06 May 2011 - 06:56 AM

View Postkenryuakuma, on 05 May 2011 - 09:29 PM, said:

However the problem is that since fixed (int* p = nums)
this is only getting the address of nums[0]. But when assigning values, the author did something like this p[i] = i; through the loop.


Why is that a 'problem'? It is perfectly legal as you have seen. As I said, the author of the example filled the array in a conventional manner. not in a pointer-address manner. So?


View Postkenryuakuma, on 05 May 2011 - 09:29 PM, said:

Besides, when we wanna reference or point to another address, aren't we supposed to assign the pointer variable to another address by doing something like this *p = &nums[1]

You have working code that does the assignment. So you can answer this yourself as to *how* you are supposed to do it. Look at the working example.


View Postkenryuakuma, on 05 May 2011 - 09:29 PM, said:

Aren't we supposed to assigning values to the pointer like this *p = i;?
We have no idea what you are *supposed* to be doing in your schoolwork.

View Postkenryuakuma, on 05 May 2011 - 09:29 PM, said:

Besides what does this mean *(p+i) = i;? I just don't get it and this has really confused me.
It is the answer to your earlier question about assigning a value using the memory address.

Look at it like any other math problem and solve inside the parenthesis first.
P is the address of the first element of the array.
i is your index counter
In the example I screen shot, we are on the 7th iteration of the loop.
P = 0x2949e10, i = 6
(P + i) therefor is 0x2949e10 + 6
So *(P + i) resolves down to the memory address 0x2949e16
then that address is set equal to i
In other words the memory address 0x2949e16 is assigned the value of 6

The loop does this

address + 0 = 0
address + 1 = 1
address + 2 = 2
address + 3 = 3
...
address + 10 = 10

This post has been edited by tlhIn`toq: 06 May 2011 - 06:57 AM

Was This Post Helpful? 1
  • +
  • -

#7 kenryuakuma  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 381
  • Joined: 14-December 08

Re: C# Array Pointer

Posted 06 May 2011 - 12:45 PM

marinus:

Thanks for your trying to help.

tlhIn`toq:

Thanks for all your efforts.

Well...The book that contains all these code is just the reference book that I use to teach myself programming because my instructor has never taught us anything like this. Therefore, if I wanna learn a little bit more, something that I have not or never been taught, I have to have a reference book, which is this book - C# 4.0 Complete Reference. SO NO ASSIGNMENT OR ANY LAZY APPROACH here. If I were to ask for help with assignments, I would have asked a different questions - something related to the assignments.

Anyway, last question:
- The reason I asked the question earlier on fixed (int* p = nums) because the author said
if we don't specify the address such as &nums[0], the pointer always points to the starting address of the array

So the question is:
Does the fixed (int* p = nums) point to only the first element[b] of the array nums, such as &nums[0] or does it point to [b]the whole array?

This is what confuses me.

This post has been edited by kenryuakuma: 06 May 2011 - 12:47 PM

Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 06 May 2011 - 01:54 PM

The answer to your question is; It points to the start of the array.

Which is what this is doing... Specifying the address of the specific element of the array. The starting address, plus the index of the element.

*(p+i)

You need to move past the idea there is only one way to do anything. There are generally lots of different ways to accomplish the same goal. That's where coding style come in.

I also really recommend you walk through that code line by line with the F10 key and look at the values with each iteration. It seems like you are trying to learn all this through theory with no hands on. Walking through the code and looking at all these values as the code is running really will make a lot of this more clear.
Was This Post Helpful? 1
  • +
  • -

#9 marinus  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 135
  • View blog
  • Posts: 575
  • Joined: 14-April 10

Re: C# Array Pointer

Posted 06 May 2011 - 01:57 PM

Pointers is discouraged in C# programming , if you are using pointers in C# its only for some optimizations and to be honest pointers in C# is not needed for a array assignment , it's not pointers main function ..

Pointers is used where there is minimal system power like embedded devices to work with memory directly ..

I think this code is misleading

Only use pointers when its a must

Pointers is the perfect solutions for Embedded Devices . Although if used correctly in C# it can improve performance a bit. Because unlike VB.NET , C# does have the capability to work with pointers declarations and Microsoft did this for a reason , where VB.NET can only use IntPtr

If you want to learn about pointers then ,
yeah try to learn it this way .


Pointers is used for http://en.wikipedia....%28computing%29

This post has been edited by marinus: 06 May 2011 - 02:15 PM

Was This Post Helpful? 0
  • +
  • -

#10 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4469
  • View blog
  • Posts: 7,783
  • Joined: 08-June 10

Re: C# Array Pointer

Posted 06 May 2011 - 02:08 PM

@marinus, the OP found the code in a book and wants to understand it:

Quote

The code was extracted from the reference book...I came across with this and don't really understand how the code work, so ask questions here.


That's valid. I also wouldn't suggest that you actually use code like this, but it's good to know that you can for that one time where you need it.
Was This Post Helpful? 0
  • +
  • -

#11 kenryuakuma  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 381
  • Joined: 14-December 08

Re: C# Array Pointer

Posted 06 May 2011 - 05:45 PM

tlhIn`toq:

- I think you have completely got me wrong and misunderstood my question. I already understand how *(p+i) works and what it does.

What I am asking is the code like this:

 fixed (int* p = nums) {
	   for(int i=0; i < 10; i++)
	         p[i] = i; // index pointer like array
	  
	   for(int i=0; i < 10; i++)
	         Console.WriteLine("p[{0}]: {1} ", i, p[i]); 


since this fixed (int* p = nums) points to the starting element of the array, getting that address, which I already know.

So p = &nums[0] but how can p(which is &num[0]) can be iterated and assigned values(turn into something like this p[i]. If we assigning new values to another array element, don't we have to have the pointer point to the address of another new elements?

I have tried the program, but p always contains the same address.
Was This Post Helpful? 0
  • +
  • -

#12 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 07 May 2011 - 04:09 AM

View Postmarinus, on 06 May 2011 - 02:57 PM, said:

Pointers is discouraged in C# programming , if you are using pointers in C# its only for some optimizations and to be honest pointers in C# is not needed for a array assignment , it's not pointers main function ..

Pointers is used where there is minimal system power like embedded devices to work with memory directly ..


There are other times. Right now I'm working with a camera API that requires a reserved memory block for the downloading of images. The way you get the image from the camera memory is supply a memory space of the right size, pass the address, the driver dumps the image as bytes, then you parse the memory to retrieve the image.

I've seen this type of approach before with hardware makers because they have support Windows, Macintosh, Linux etc. across a variety of languages from C++, C#, Objective-C with a set of fairly consistent approaches.
Was This Post Helpful? 0
  • +
  • -

#13 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 07 May 2011 - 04:15 AM

View Postkenryuakuma, on 06 May 2011 - 06:45 PM, said:

tlhIn`toq:

- I think you have completely got me wrong and misunderstood my question. I already understand how *(p+i) works and what it does.

What I am asking is the code like this:

 fixed (int* p = nums) {
	   for(int i=0; i < 10; i++)
	         p[i] = i; // index pointer like array
	  
	   for(int i=0; i < 10; i++)
	         Console.WriteLine("p[{0}]: {1} ", i, p[i]); 


since this fixed (int* p = nums) points to the starting element of the array, getting that address, which I already know.

So p = &nums[0] but how can p(which is &num[0]) can be iterated and assigned values(turn into something like this p[index]. If we assigning new values to another array element, don't we have to have the pointer point to the address of another new elements?

I have tried the program, but p always contains the same address.


You seem to be completely fixated on changing the value of p, rather than calculating the address of the next element.

p is the starting address of the array. You would not change that. To get an address of the next element you calculate it from p. You say you understand what *(p+i) is doing but your question seems into indicate otherwise. I've said it every way I can. If you still aren't getting it, its time to go to your professor.

tlhIn`toq said:

P is the address of the first element of the array.
i is your index counter
In the example I screen shot, we are on the 7th iteration of the loop.
P = 0x2949e10, i = 6
(P + i) therefor is 0x2949e10 + 6
So *(P + i) resolves down to the memory address 0x2949e16
then that address is set equal to i
In other words the memory address 0x2949e16 is assigned the value of 6

The loop does this

StartingAddress + 0 = 0
StartingAddress + 1 = 1
StartingAddress + 2 = 2
StartingAddress + 3 = 3
...
StartingAddress + 10 = 10

This post has been edited by tlhIn`toq: 07 May 2011 - 04:24 AM

Was This Post Helpful? 0
  • +
  • -

#14 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5481
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: C# Array Pointer

Posted 07 May 2011 - 04:20 AM

View Postkenryuakuma, on 05 May 2011 - 09:29 PM, said:

The code was extracted from the reference book...I came across with this and don't really understand how the code work, so ask questions here.


I will point out that a reference book is not a teaching book.

A dictionary is a reference book, but was not meant to teach you the English language. There are no tutorials or instructions about the syntax of the language, when and how to best use certain constructs and so on.

The same is happening here. Your reference book is not teaching you. I would recommend you quit trying to use it for a purpose it wasn't intended and pick up a self-teaching book.

I would recommend you start with "Hello World" just like the other million+ coders out there. Then work your way up to the more advanced tasks like this.

The problem with taking on large, complex tasks like this when you are new to coding is that
  • it will frustrate you to the point of quitting,
  • you don't know enough about coding to know where to start or in what direction to design your program
  • You risk learning via the 'Swiss cheese' method where you only learn certain bits and pieces for the one project but have huge holes in your education.



Standard resources, references and suggestions for new programmers.

I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard experimentation - or you can learn by doing the tutorials and following a good "How to learn C#" book.

Free editions of Visual Studio 2010

May I suggest picking up a basic C# introductory book? There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" type books at your local book seller or even public library.

D.I.C. C# Resource page Start here
Intro to C# online tutorial then here...
C# control structures then here.
MSDN Beginner Developer video series
MSDN video on OOP principals, making classes, constructors, accessors and method overloading
MSDN Top guideline violations, know what to avoid before you do it.

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Quick and easy custom events
Bulding an application - Part 1
Building an application - Part 2
Passing values between forms/classes

Working with environmental variables

Debugging tutorial
Debugging tips
Great debugging tips
It still doesn't work, article

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.
Reading a text file tutorial.


These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the 500+ MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on

Was This Post Helpful? 1
  • +
  • -

#15 Jeff H  Icon User is offline

  • D.I.C Regular

Reputation: 112
  • View blog
  • Posts: 308
  • Joined: 30-January 11

Re: C# Array Pointer

Posted 07 May 2011 - 07:18 AM

Maybe this will help.
If you need more detail I can research it.

Here is a good link http://www.augustcou...torial/arr.html

I can not say this true or correct but I would think something similar is happening under hood.

So if you understand *(p + 4) as 4 is the offset

'[]' is a subscript operator.

In C++ when the compiler sees p[4] it converts it to *(p + 4)

In the code below it assigns the integer value of the index then reverses it, but the main point is to look at
line 13 nums[i] = i;
line 27 i[nums] = j;

both work since *(nums + i) is the same as *(i + nums)

#include <iostream>

using namespace std;


int main()
    {

    int nums[10];

    for (int i =0; i <10; i++)
        {
        nums[i] = i;        
        }
            
    for (int i = 0; i <10; i++)
        {
       cout << nums[i] << "  address = " << (unsigned int)&nums[i] << "\n";     
        }

    cout << "\n\n\n" << endl;
        
    int j = 9;
    
    for (int i =0; i <10; i++, j--)
        {
        i[nums] = j;        
        }


    
    for (int i = 0; i <10; i++)
        {
       cout << nums[i] << "  address = " << (unsigned int)&nums[i] << "\n";          
        }

    system("PAUSE");
    return 0;
    }



Back to C#
This is the code originally posted updated.
Notice how the address are same using either method and how they increase depending on data type.[A int is 4bytes(32bit----8x4=32) and long is 8bytes(64bit---8x8=64)]
Each address holds 8bits or a byte so for a int it increases by 4 and for long it increases by 8.
using System;

public class PtrIndexDemo
{

    unsafe public static void Main()
    {
        int[] nums = new int[10];

        Console.WriteLine("*************Using int**********");
        Console.WriteLine("Index pointer like array.");
        fixed (int* p = nums)
        {
            for (int i = 0; i < 10; i++)
                p[i] = i; // index pointer like array 

            for (int i = 0; i < 10; i++)
            {
                int* ptrInt = &p[i];
                IntPtr address = (IntPtr)ptrInt;
                Console.WriteLine("p[{0}]: {1} {2}", i, p[i], address.ToString());

            }

        }


        // use pointer arithmetic 
        Console.WriteLine("\nUse pointer arithmetic.");
        fixed (int* p = nums)
        {
            for (int i = 0; i < 10; i++)
                *(p + i) = i; // use pointer arithmetic 

            for (int i = 0; i < 10; i++)
            {
                int* ptrInt = &(*(p + i));
                IntPtr address = (IntPtr)ptrInt;
                Console.WriteLine("*(p+{0}): {1} address = {2}", i, *(p + i), address.ToString());
            }

        }


        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("*************Using long**********");
        long[] longs = new long[10];


        Console.WriteLine("Index pointer like array.");
        fixed (long* p = longs)
        {
            for (int i = 0; i < 10; i++)
                p[i] = i; // index pointer like array 

            for (int i = 0; i < 10; i++)
            {
                long *ptrLong = &p[i];
                IntPtr address = (IntPtr)ptrLong;
                Console.WriteLine("p[{0}]: {1} address = {2}", i, p[i], address.ToString());

            }

        }


        // use pointer arithmetic 
        Console.WriteLine("\nUse pointer arithmetic.");
        fixed (long* p = longs)
        {
            for (int i = 0; i < 10; i++)
                *(p + i) = i; // use pointer arithmetic 

            for (int i = 0; i < 10; i++)
            {
                long *ptrInt = &(*(p + i));
                IntPtr address = (IntPtr)ptrInt;
                Console.WriteLine("*(p+{0}): {1} {2}", i, *(p + i), address.ToString());
            }

        }
        Console.ReadLine();
    }

}

Attached image(s)

  • Attached Image
  • Attached Image

This post has been edited by Jeff H: 07 May 2011 - 07:22 AM

Was This Post Helpful? 3
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2