Pointer arithmetic with an array

pointer arithmetic in c
pointer arithmetic in c - geeksforgeeks
pointer arithmetic in c pdf
array of pointers in c
pointer arithmetic vs array indexing
pointer arithmetic in c in hindi
operations on pointers in c
c pointer arithmetic subtraction

I am trying to write a simple program in C that stores elements in a pointer. I am getting junk values when I print the elements of the array.

Here is the code:

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

#define MAX 5

int main(int argc, char const *argv[]) {

    int* a = (int*)malloc(MAX * sizeof(int));
    int* b = NULL;
    int* const maxAddress = a + MAX;

    if(a != NULL) {
        for(int index = 0; b = a, b < maxAddress; index++) {
            *(a + index) = index;
            printf("Value: %d, Index: %d\n", *(a + index), index);
            a++;
        } 
    }   

    printf("\n\n");

    for(int index = 0; index < MAX; index++) // Getting junk values here
        printf("Index: %d, Value: %d, Address: %p\n", index, *(a + index), a + index);

    return 0;
}

Here is the corrected code: b should be initialized before the the loop. the for loop was incorrect you should increment b not a in the loop

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

#define MAX 5

int main(int argc, char const *argv[]) {

    int* a = (int*)malloc(MAX * sizeof(int));
    int* b = a;
    int* const maxAddress = a + MAX;

    if (a != NULL) {
        for (int index = 0; b < maxAddress; index++) {
            *(a + index) = index;
            printf("Value: %d, Index: %d\n", *(a + index), index);
            b++;
        }
    }

    printf("\n\n");

    for (int index = 0; index < MAX; index++) // Getting junk values here
        printf("Index: %d, Value: %d, Address: %p\n", index, *(a + index), a + index * sizeof(int));

    return 0;
}

C - Pointer arithmetic, Pointer arithmetic. The C++ language allows you to perform integer addition or subtraction operations on pointers. If ptr points to an integer,  A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and - To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address

You have two independent increments going on. In the for loop you do index++, while in the end of the loop you increment a++. That means your first write is to a[0], your next is to a[1 + 1], etc. Basically, you are skipping every other element.

To avoid doing this increment a or index, but not both. Since you want the values of index to progress, I would recommend removing the line a++.

The variable b is not used except in the beginning of the loop, so the condition b = a, b < maxAddress seems pointless. It could be written as a < maxAddress. If I had so guess, b was being used in a fuller version of the code to retain the previous value of a for the next iteration.

6.8a, Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes  Incrementing a Pointer. We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array −

The syntax *(a + index) is equivalent to a[index]; the latter indicates your intent with the code more clearly.

If we break down what you're doing with the lines index++ (in your for loop declaration) and a++ in the body of your loop, you will observe that you're accessing memory you didn't actually allocate for a:

Loop Iteration #0 (a = allocated address index = 0):

*(a + index) accesses a[0]
a[0]   a[1]   a[2]    a[3]    a[4]
 0      ?      ?       ?        ?

Loop Iteration #1 (a = alloc+1 index = 1):

*(a + index) accesses a[2]
a[0]   a[1]   a[2]    a[3]    a[4]
 0      ?      1       ?       ?

You begin to write past the array at iteration #3:

*(a + index) accesses a[6]
a[0]   a[1]   a[2]    a[3]    a[4]     | MEMORY NOT BELONGING TO a
 0      ?      1       ?       ?                   3?

Also, after your initial for loop where you incremented the pointer a to the end of your allocated amount, you try to access it again without resetting it to its initial value, so the values you access are not even the ones you (thought you had) assigned.

This is especially bad for memory allocated with malloc since you usually later free it, but you can't do that without a pointer to the beginning of your allocated memory block.

Solution:

Do not increment a in your initial for loop and use the correct truth condition:

for(int index = 0; (a + index) < maxAddress; index++) 
// Also valid: ...; index < MAX; ...
{
        *(a + index) = index;
        printf("Value: %d, Index: %d\n", *(a + index), index);
} 

Sum of array using pointer arithmetic, Once you understand pointers, pointer arithmetic is easy. So, really when we specify an element of an array with array[n], that's just syntactic  When you're doing pointer arithmetic, you have to remember how big the array the pointer points into is, so that you don't ever point outside it. If the array a has 10 elements, you can't access a[50] or a[-1] or even a[10] (remember, the valid subscripts for a 10-element array run from 0 to 9).

Pointer Arithmetic, We can traverse an array by using the increment operation on a pointer which will keep pointing to every element of the array, perform some operation on that, and  Pointer increment decrement operation memory representation Example program to perform pointer increment and decrement. Array in memory are stored sequentially, hence is the best example to demonstrate pointer increment, decrement operations.

Pointer Arithmetic in C, Given an array arr[ARRAY_SIZE] we can get the address of the i -th element by arr + i as arr works as a pointer to the first element of the array. This is true for any​  That is your full pointer notation for accessing any element within a sequential block of memory in a simulated 2D array manner and that is what is happening behind the scene when you write array[x][y]. Now let's talk pointer arithmetic. When you declare a pointer, you are declaring a pointer to a specific type (except in the case of void

Pointer Arithmetic Part 1 - How to play with pointers in C, Pointer arithmetic is another way to traverse through an array. Again, it is much more common in the C world of programmers. Most faculty at UWB don't want to  16 bit Machine (Turbo C). In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2 bytes.But when we perform any arithmetic function like increment on a pointer, changes occur as per the size of their primitive data type.

Comments
  • You may want to format your code by indenting it by four spaces, and to add a language tag, such as C. Use the edit button beneath your question, hilight your code, and press the {} toolbar button.
  • I fixed it this time, but it does really help to use the code format. Good job delivering a complete code example.
  • I am not sure I understand why you say "It seems to work" when the remainder of the question shows quite the opposite. Overall nicely written question though. +1
  • What is b for? Why is maxAddress ? Most important question, what does a++ do to the pointer of the beginning of your array ?
  • don't cast the result of malloc in C
  • Thanks for your response Paul :)
  • Note here that a isn't incremented. If you increment a, you lose track of where the original array started. That's where the weird values came from.
  • Note that even though this code does check for the null-ness of a when it is being populated, that is not checked for when the contents of a are printed in the next loop. This is best handled by checking if(a == NULL) { /* report alllocation error and exit */ } rather than if(a != NULL) { /* do stuff */ }
  • Thanks Mad Physicist