Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with pointer math in C

Tags:

c

pointers

I have a question, I've started to learn pointers today and something weird came up: according to my guide, by adding 1 to the created pointer the program will go tho the next variable in the memory. it is seen when the address of point + 1 is printed, but when I try it to print the value of *(point + 1) it just prints the address of d?

  int d = 5;
    int e = 12;
    int *point = &d;
    printf("\n\n%u %i\n%u", point, *point, point + 1);
    printf("\n%i", *(point + 1)); 

why is that happening? btw I'm using codeblocks

like image 903
Medvednic Avatar asked Jun 16 '26 14:06

Medvednic


2 Answers

int *point = &d;

Evaluating:

*(point + 1)

invokes undefined behavior in C. point + 1 is not a pointer to a valid object.

like image 96
ouah Avatar answered Jun 19 '26 03:06

ouah


Your problem is: you're advancing a pointer with

point + 1

this is undefined behavior in C because point is just a pointer to an integer not an array of integers and you're asking the next value... no-one (except the operating system) knows what's in the next integer cell after the one you're pointing... and so: undefined data and undefined behavior.

The following is an interactive (click on the ideone link) example for how to deal with pointer arithmetic properly, i.e. by advancing pointers on memory you already control or know what's in there

#include <stdio.h>

int main(void) {

    int arrayOfIntegers[] = {5,12};
    printf("First: %d, second: %d\n", *arrayOfIntegers, *(arrayOfIntegers + 1));

    return 0;
}

http://ideone.com/ROI1Fp

like image 27
Marco A. Avatar answered Jun 19 '26 03:06

Marco A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!