Teciex Teciex - 3 months ago 8
C Question

Pointer is incrementing twice

I have created a char array of size 4 in C and i am trying to read the value of char array from the pointer/ memory address of the pointer. I am trying to increment the pointer named a cpointer once but when i run the code the pointer is incrementing twice(my assumption) because the output which i am getting is skiping the immediate next char.

#include<stdio.h>

int main(){

char c[4] = {'A','B','C','D'};
char *cpointer = &c ;

for(int i=0; i<4 ;i++){
read(&cpointer[i]);
cpointer++;
}
return 0;
}

void read(int *n){
printf("c array address - %u \n", n);
printf("Reading c array address - %c \n", *n);
}


Output which i am getting for the above code -

c array address - 6749760
Reading c array address - A
c array address - 6749762
Reading c array address - C
c array address - 6749764
Reading c array address -
c array address - 6749766
Reading c array address -


When i am incrementing the cpointer counter in read function then i am receiving the correct output.

Increment inside read function -
Code-

#include<stdio.h>

int main(){

char c[4] = {'A','B','C','D'};
char *cpointer = &c ;

for(int i=0; i<4 ;i++){
read(&cpointer[i]);
}
return 0;


}

void read(int *n){
printf("c array address - %u \n", n);
printf("Reading c array address - %c \n", *n);
n++;
}


Output for the above code-

c array address - 6749744
Reading c array address - A
c array address - 6749745
Reading c array address - B
c array address - 6749746
Reading c array address - C
c array address - 6749747
Reading c array address - D


I am a beginner in C. I am not able to figure out why in my previous code where i am trying to increment cpointer once is getting incremented twice where as in the below code where i am incrementing cpointer is getting incremented once (which i want) and later resulting in correct output.

Answer
for(int i=0; i<4 ;i++){
    read(&cpointer[i]);
    cpointer++;
}

take i = 0. What do you get?

 read(&cpointer[0]);
 cpointer++;

But now cpointer has moved one byte forward right? So when i=1, what do you get?

 read(&cpointer[1]); // but c pointer here is already increased due to previous loop - so index 1 causes it to get increased further more
 cpointer++;

Also you seem to have undefined behaviors, first of all here:

printf("c array address - %u \n", n);
printf("Reading c array address - %c \n", *n);
  • when you dereference n it will read four bytes from memory given size of int is 4, now if you are say in the middle of array, how can we read four bytes from memory? we can't, because there are only two bytes left.
  • Also to print address you should use %p instead of %u - and cast pointer inside printf to void*.

You are much better of using following function instead:

void read(char *n){
    printf("c array address - %p \n", (void*)n);
    printf("Reading c array address - %c \n", *n);
    n++;
}
Comments