Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - pointer arithmetic, unexpected results

Tags:

c

Here is an example code:

int* arr = (int*)malloc(2 * sizeof(int));

arr = arr + 1;
*arr = 11;
arr[-1] = 22;

int x = arr[0]; // x = 11
int y = arr[1]; // y = 194759710

After a memory allocation arr pointer is incremented. I have expected to get the following results:

x == 22
y == 11

Could you explain how it works ?

like image 816
Irbis Avatar asked Jan 21 '26 22:01

Irbis


1 Answers

When you set x and y, you forgot that arr no longer points on allocated memory.

This code do what you want:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    int* arr = (int*)malloc(2 * sizeof(int));
    int *original = arr;

    arr = arr + 1;

    *arr = 11;
    arr[-1] = 22;

    int x = original [0]; // x = arr[-1]
    int y = original [1]; // y = arr[0]

    printf("%d, %d\n", x, y);
}
like image 109
Mathieu Avatar answered Jan 23 '26 13:01

Mathieu



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!