Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer vs. variable, Objective-C

Tags:

c

objective-c

I have some difficulties grasping some concepts. Grateful for help.

Let's say you have the following piece of code:

int *intPtr;   // creates a pointer
int count = 10; // initiates an intiger variable
intptr = &count; // ??

The & operator gives the address to a variable, in this case the integer count. The address is then assigned to the intptr. My question is: Why is intptr = count; not sufficient. I know that count is a variable and intptr is a pointer, but isn´t a variable also just referring to some place in memory?

Hans

like image 813
salomons Avatar asked Aug 06 '10 13:08

salomons


2 Answers

count refers to the VALUE of the variable. You don't want to assign the value of count to intptr, you want to assign the address of count. Thus the & operator is used.

If you do intptr = count, you'd be pointing to memory address 10 in this case, which is sure to be in system memory, not your application memory and you'd crash.

like image 106
wadesworld Avatar answered Nov 16 '22 11:11

wadesworld


It is important to understand that pointers have actually a different data type.

A int variable will hold integer values.

A pointer variable will hold memory addresses.

So it is not right to assign an int variable to a pointer variable (as you suggested intptr = count;)

I believe using a typedef could help you better understand the difference.

Here's a small example:

#include <stdio.h>

typedef int* int_pointer;

int main() {

    int n; // integer
    int_pointer p; // pointer

    n = 5;

    p = &n; // p's value is now n's address

    *p = *p + 1; // add 1 to the value stored at the location that p points to
                 // and put that value back in the same location

    printf("n = %d\n", n);
    printf("*p = %d\n", *p);

    return 0;
}

This program will print

n = 6
*p = 6
like image 6
Florin Avatar answered Nov 16 '22 13:11

Florin