How to access structure elements using Pointers in C#
Last Updated :
26 Feb, 2019
Unlike C/C++, Structures in C# can have members that are methods, fields, indexers, operator methods, properties or events. The members can have access specifiers as public, private, and internal.
Pointers are variables that store the addresses of the same type of variable i.e. an int pointer can store an address of an integer, a char pointer can store an address of a char and similarly for all other data types, fundamental or user-defined.
You can access a structure member using pointers, of type structure, in the following ways;
1) Using the arrow operator: If the members of the structure are public then you can directly access them using the arrow operator ( -> ). If they are private then you can define methods for accessing the values and use pointers to access the methods. The arrow operator can be used to access structure variables as well as methods.
Syntax:
PointerName->memberName;
Example:
using System;
namespace GFG {
struct Student
{
public int rno;
public double marks;
public Student( int r, double m)
{
rno = r;
marks = m;
}
};
class Program {
static void Main( string [] args)
{
unsafe
{
Student S1 = new Student(1, 95.0);
Student S2 = new Student(2, 79.5);
Student* S1_ptr = &S1;
Student* S2_ptr = &S2;
Console.WriteLine( "Details of Student 1" );
Console.WriteLine( "Roll Number: {0} Marks: {1}" ,
S1_ptr -> rno, S1_ptr -> marks);
Console.WriteLine( "Details of Student 2" );
Console.WriteLine( "Roll Number: {0} Marks: {1}" ,
S2_ptr -> rno, S2_ptr -> marks);
}
}
}
}
|
Output:
2) Using Dereferencing operator: You can also access structure elements using the dereferencing operator on the pointer, which is using an asterisk to dereference the pointer and then using the dot operator to specify the structure element.
Syntax:
(*PointerName).MemberName;
Example:
using System;
namespace GFG {
struct Employee{
public int Eid
{
get ;
set ;
}
public double Salary
{
get ;
set ;
}
}
;
class Program {
static void Main( string [] args)
{
unsafe
{
Employee E1;
Employee* ptr = &E1;
(*ptr).Eid = 1101;
(*ptr).Salary = 1000.00;
Console.WriteLine( "Details of Employee" );
Console.WriteLine( "Employee Id: {0}\nSalary: {1}" ,
(*ptr).Eid, (*ptr).Salary);
}
}
}
}
|
Output:
Note: To compile unsafe code on Visual Studio (2012), Go to Project –> ProjectName Properties –> Build –> Check the “Allow unsafe code” box.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...