Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
c - pointer arithmetic, unexpected results

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 ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The y assignment is incorrect. You only have 2 allocated items so you cannot first increment the pointer by one, then de-reference that pointer with [1], because that gives a 3rd element which doesn't exist.

over 4 years ago · Santiago Trujillo Report

0

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);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!