Benefits of pointers?

后端 未结 11 1527
不知归路
不知归路 2021-01-03 23:40

I recently developed an interest in C programming so I got myself a book (K&R) and started studying.

Coming from a University course in Java (basics), pointers a

11条回答
  •  迷失自我
    2021-01-04 00:11

    Considering that you're coming from a Java background, here's the simplest way to get your head around what use pointers have.

    Let's say you have a class like this in Java:

    public class MyClass {
        private int myValue;
    
        public int getMyValue() { return myValue; }
        public void setMyValue(int value) { myValue = value; }
    }
    

    Here's your main function, that creates one of your objects and calls a function on it.

    public static void Main(String[] args) {
        MyClass myInstance = new MyClass();
    
        myInstance.setMyValue(1);
        System.out.printLn(myInstance.getMyValue()); // prints 1
    
        DoSomething(myInstance);
        System.out.printLn(myInstance.getMyValue()); // prints 2
    }
    
    public static void DoSomething(MyClass instance) {
        instance.setMyValue(2);
    }
    

    The myInstance variable you declared in Main is a reference. It's basically a handle that the JVM uses to keep tabs on your object instance. Now, let's do the same thing in C.

    typedef struct _MyClass
    {
        int myValue;
    } MyClass;
    
    void DoSomething(MyClass *);
    
    int main()
    {
        MyClass myInstance;
    
        myInstance.myValue = 1;
        printf("i", myInstance.myValue); // prints 1
    
        MyClass *myPointer = &myInstance; // creates a pointer to the address of myInstance
    
        DoSomething(myPointer);
        printf("i", myInstance.myValue); // prints 2
    
        return 0;
    }
    
    void DoSomething(MyClass *instance)
    {
        instance->myValue = 2;
    }
    

    Of course, pointers are much more flexible in C, but this is the gist of how they work in a Java sort of way.

提交回复
热议问题