Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,940 questions

51,877 answers

573 users

How to use pointer arithmetic to tell where I am in an array with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
 
int main() {
    int size = 10;
     
    int* p = (int*) malloc(sizeof(int) * size);
     
     if (p == NULL) {
        puts("Memory error");
        return -1;
    }
     
    printf("first element: %p\n", p); // first element
    printf("elements number: %d\n", p - p); 
     
    int *location = p + 1;
    printf("second element: %p\n", location); // second element
    printf("elements number: %d\n", location - p); 
     
    location += 1;
    printf("third element: %p\n", location); // third element
    printf("elements number: %d\n", location - p); 
     
    location += 1;
    printf("fourth element: %p\n", location); // fourth element
    printf("elements number: %d\n", location - p); 
 
    location = p + (size / 2);
    if (size % 2 == 0) {
        location--;
    }
    printf("middle element: %p\n", location); // middle element
    printf("elements number: %d\n", location - p); 
    printf("total elements up to center: %d\n", location - p); 
     
    location = p + (size - 1);
    printf("last element: %p\n", location); // last element
    printf("elements number: %d\n", location - p); 
 
    free(p);
 
    return 0;
}
 
 
 
/*
run:
 
first element: 0x2b2b72a0
elements number: 0
second element: 0x2b2b72a4
elements number: 1
third element: 0x2b2b72a8
elements number: 2
fourth element: 0x2b2b72ac
elements number: 3
middle element: 0x2b2b72b0
elements number: 4
total elements up to center: 4
last element: 0x2b2b72c4
elements number: 9
 
*/

 



answered Feb 16, 2025 by avibootz
edited Feb 16, 2025 by avibootz

Related questions

1 answer 286 views
1 answer 227 views
1 answer 162 views
162 views asked Jul 11, 2019 by avibootz
1 answer 314 views
1 answer 753 views
1 answer 165 views
2 answers 156 views
...