Understanding pointers?

后端 未结 6 491
北恋
北恋 2020-12-11 11:25

As the title suggests, I\'m having trouble understanding exactly what a pointer is and why they\'re used. I\'ve searched around a bit but still don\'t really understand. I\'

6条回答
  •  借酒劲吻你
    2020-12-11 11:46

    To answer each of your questions:

    (1) From what I understand, a variable with an asterisks in front points to an address in memory?

    You can see it that way more or less. The asterisk is a dereference operator, which takes a pointer and returns the value at the address contained in the pointer.

    (2) I don't quite understand why you'd use a pointer to a value instead of just using the value itself.

    Because pointers allow different sections of code to share information, better than copying the value here and there, and also allows pointed variables or objects to be modified by called function. Further, pointers enabled complex linked data structures. Read this short tutorial Pointers and Memory.

    (3) Why wouldn't you use pointers to integers and other basic data types?

    String is a pointer, unlike int or char. A string is a pointer that points to the starting address of data that contains the string, and return all the value from the starting address of the data until an ending byte.

    string is a more complex datatype than char or int, for example. In fact, don't think sting as type like int of char. string is a pointer that points to a chunk of memory. Due to its complexity, having a Class like NSString to provide useful functions to work with them becomes very meaningful. See NSString.

    When you use NSString, you do not create a string; you create an object that contains a pointer to the starting address of the string, and in addition, a collection of methods that allows you to manipulate the output of the data.

提交回复
热议问题