What is the counterpart of this C pointer programme in C#?

Joined
Jul 29, 2008
Messages
7
Reaction score
1
I'd like to know how the following programme on pointer written in C can be written in C#, especially how to use the keywords in the C programme like &i and *p in C#. Please clarify.

C:
#include <stdio.h>

void f(int *p, int *q)
{
    p = q;
    *p = 2;
}

int i = 0, j = 1;

int main()
{
    f(&i, &j);
    printf("%d %d \n", i, j);
    return 0;
}
 
Joined
Mar 3, 2021
Messages
240
Reaction score
30
Pointers work largely the same, but code using them must be marked as unsafe. Taking the address of static variables is a different issue ("CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer"). So, that part is wrapped in a fixed block with temporary variables.

Code:
using System;

class Program
{
    static int i = 0, j = 1;
    public static unsafe void f(int* p, int* q)
    {
        p = q;
        *p = 2;
    }

    static unsafe void Main(string[] args)
    {
        fixed (int* ip = &i, jp = &j){ 
            f(ip, jp);
        }
        Console.WriteLine("{0} {1}", i, j);
    }
}
 
Joined
Jul 29, 2008
Messages
7
Reaction score
1
Pointers work largely the same, but code using them must be marked as unsafe. Taking the address of static variables is a different issue ("CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer"). So, that part is wrapped in a fixed block with temporary variables.
So what I can infer is that, in C#, besides using the ref keyword, we can also use the concepts of address-of and indirection operators from traditional C. It's only that these concepts are shifted under the "unsafe category coding" where we need to use them with the fixed and unsafe keywords. Also, programmers are suggested to use them under exceptional circumstances with caution.

Thanks for the explanation. I was exactly looking for such help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top