Pointer Syntax confusing me.

Discussion in 'Mac Programming' started by bmcgonag, Oct 20, 2011.

  1. bmcgonag macrumors 65816

    bmcgonag

    Joined:
    Mar 20, 2007
    Location:
    Texas
    #1
    I"m sure this is extremely basic, but maybe someone can give me the dummed down version.

    I'm new to OOP, and Objective-C, so bare with me.

    I understand that in

    Code:
    NSString *string;
    I'm telling the variable string to point to the NSString object. I understand that a memory location has been or will be allocated for the data of NSString, and that I just use string to point to that.

    What I don't understand is sometimes i see the following things:

    NSString * string;

    or

    NSString* string;

    and (NSString *)string;

    this is all quite confusing, and I can't really find any reference to the differences / meanings of these different ways of typing these things.

    Any help / direction to links that give the basic rules of pointers and syntax are greatly appreciated.
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    The first two are not different: the spaces don't matter. The third is a cast.
     
  3. willieva macrumors 6502

    Joined:
    Mar 12, 2010
    #3
    When you make the declaration:
    int i;
    you are creating a variable of type int.
    int* i;
    is creating a variable of type int* which is an int pointer. You have created a variable that holds the address of an int.

    As you've seen you can also type:
    int *i;

    int* i; and int *i; are the same. Personally I prefer to use the first form since it more concretely shows you want to create something of type int*, which is quite different then creating an int. You'll see both, so get to used to both forms.

    BTW, you can also make a cast like:
    (int*)
     
  4. bmcgonag thread starter macrumors 65816

    bmcgonag

    Joined:
    Mar 20, 2007
    Location:
    Texas
    #4
    FINALLY!

    Thank you so much for explaining this. They cover 'casts', they cover 'pointers', and I know that these are important, but they didn't cover the cast using the *, so it never donned on me that this was what they were doing.

    This makes so much more sense now, and makes the sample code so much easier to comprehend.

    thank you again,
     

Share This Page