Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got confused with pointers in C

Tags:

c

pointers

I just reached pointers in my textbook but it doesn't explain good enough, so i need some help.

I know what pointers are and what they do. for example i understand the following example very well:

#include <stdio.h>

int main ()
{
    int num = 5;
    int *point;

    point = &num;

    *point = 8;

    printf("%d %d", num, *point);

    return 0;
}

point is pointing to num (storing num's address as its value). and then i'm dereferencing point to change the original value of num.

now consider the sightly modified version of the same example:

#include <stdio.h>

int main ()
{
    int num = 5;
    int *point;

    point = 8;

    printf("point: %d\n", point);

    printf("sum (%d) = num (%d)+ point (%d)", num+point, num, point);

    return 0;
}

I have a couple of questions:

1- why is it even possible to assign a normal value (8) to a pointer (point)? aren't pointers supposed to store only addresses to other stuff? what is happening in line 8?

2- i compiled the code and for the second printf it shows : sum (28) = num (5) + point (8) why sum equals to 28? 5+8 is 13. what is happening?

like image 543
ufosecret Avatar asked Nov 29 '22 14:11

ufosecret


2 Answers

In your second example you are assigning 8 to your pointer. I hope you got a good warning from your compiler. But you can assign 8. Just don't dereference it. You'll probably get a segmentation fault or worse. The sum of num+point makes perfect sense. It's called pointer arithmetic. point is a pointer to integer. An int on your machine is 4 bytes. The sum of num + point is (5 * sizeof(int)) + 8, which is 28 on your system.

like image 43
Richard Pennington Avatar answered Dec 01 '22 05:12

Richard Pennington


You can point point at memory address 8 (or 0x00000008). It is equivalent to point = (int*)8; I get a friendly <Unable to read memory> error because I'm using a c++ and I assume it's protecting me from my foolishness.

Why does 5 + 8 = 28? If you add a number n to a pointer of type T, you move this pointer by n elements of type T. Your machine is dealing with 32 bit ints , which are of size 4 bytes, so 8 + ( 5 * 4) = 28.

like image 129
Nathan Cooper Avatar answered Dec 01 '22 03:12

Nathan Cooper